使用框架编写Android程序

时间 : 14-09-17 栏目 : Android, 移动开发 作者 : noway 评论 : 0 点击 : 479 次

AndroidAnnotations这个开源项目为android程序的编写提供了一个新的思路,他们自己称之为框架,我觉得很像struts2的注解方式,下面是这个项目在github上面的地址
https://github.com/excilys/androidannotations
下面的代码是一个例子

Java代码  收藏代码
  1. package com.googlecode.androidannotations.helloworldeclipse;  
  2.   
  3. import java.util.Date;  
  4. import java.util.concurrent.TimeUnit;  
  5.   
  6. import android.app.Activity;  
  7. import android.app.Notification;  
  8. import android.app.NotificationManager;  
  9. import android.app.PendingIntent;  
  10. import android.content.Intent;  
  11. import android.database.sqlite.SQLiteDatabase;  
  12. import android.os.Bundle;  
  13. import android.util.Log;  
  14. import android.view.MotionEvent;  
  15. import android.view.View;  
  16. import android.view.Window;  
  17. import android.view.WindowManager;  
  18. import android.widget.EditText;  
  19. import android.widget.TextView;  
  20. import android.widget.Toast;  
  21.   
  22. import com.googlecode.androidannotations.annotations.Background;  
  23. import com.googlecode.androidannotations.annotations.Click;  
  24. import com.googlecode.androidannotations.annotations.EActivity;  
  25. import com.googlecode.androidannotations.annotations.LongClick;  
  26. import com.googlecode.androidannotations.annotations.SystemService;  
  27. import com.googlecode.androidannotations.annotations.Touch;  
  28. import com.googlecode.androidannotations.annotations.Transactional;  
  29. import com.googlecode.androidannotations.annotations.UiThread;  
  30. import com.googlecode.androidannotations.annotations.ViewById;  
  31. import com.googlecode.androidannotations.annotations.res.BooleanRes;  
  32. import com.googlecode.androidannotations.annotations.res.ColorRes;  
  33. import com.googlecode.androidannotations.annotations.res.StringRes;  
  34.   
  35. @EActivity(R.layout.my_activity) //布局文件在这里声明,不用在setContentView  
  36. public class MyActivity extends Activity {  
  37.   
  38.     @ViewById  //控件这样标注,由于是IOC模式,因此不需要自己实例化  
  39.     EditText myEditText;  
  40.   
  41.     @ViewById(R.id.myTextView) //提供id来生成控件,如果不指定ID,默认以控件名进行查找,如上面的myEditText  
  42.     TextView textView;  
  43.   
  44.     @StringRes(R.string.hello)  //资源  
  45.     String helloFormat;  
  46.   
  47.     @ColorRes  
  48.     int androidColor;  
  49.   
  50.     @BooleanRes  
  51.     boolean someBoolean;  
  52.   
  53.     @SystemService  
  54.     NotificationManager notificationManager;  
  55.   
  56.     @SystemService  
  57.     WindowManager windowManager;  
  58.   
  59.     /** 
  60.      * AndroidAnnotations gracefully handles support for onBackPressed, whether 
  61.      * you use ECLAIR (2.0), or pre ECLAIR android version. 
  62.      */  
  63.     public void onBackPressed() {  
  64.         Toast.makeText(this"Back key pressed!", Toast.LENGTH_SHORT).show();  
  65.     }  
  66.       
  67.     @Override  
  68.     protected void onCreate(Bundle savedInstanceState) {  
  69.         super.onCreate(savedInstanceState);  
  70.         // windowManager should not be null  
  71.         windowManager.getDefaultDisplay();  
  72.         requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);  
  73.     }  
  74.   
  75.   
  76.     @Click //事件控制,可以以按钮的id作为方法名,同时支持的事件还有onLongClick,onTextChange等  
  77.     void myButtonClicked() {  
  78.         String name = myEditText.getText().toString();  
  79.         setProgressBarIndeterminateVisibility(true);  
  80.         someBackgroundWork(name, 5);  
  81.     }  
  82.   
  83.     @Background //开启新线程后台运行,注意不要引用UI控件,而且返回值类型一定是void  
  84.     void someBackgroundWork(String name, long timeToDoSomeLongComputation) {  
  85.         try {  
  86.             TimeUnit.SECONDS.sleep(timeToDoSomeLongComputation);  
  87.         } catch (InterruptedException e) {  
  88.         }  
  89.   
  90.         String message = String.format(helloFormat, name);  
  91.   
  92.         updateUi(message, androidColor);  
  93.   
  94.         showNotificationsDelayed();  
  95.     }  
  96.   
  97.     @UiThread //UI线程  
  98.     void updateUi(String message, int color) {  
  99.         setProgressBarIndeterminateVisibility(false);  
  100.         textView.setText(message);  
  101.         textView.setTextColor(color);  
  102.     }  
  103.   
  104.     @UiThread(delay=2000)  //可以设置延时时间,以毫秒为单位  
  105.     void showNotificationsDelayed() {  
  106.         Notification notification = new Notification(R.drawable.icon, "Hello !"0);  
  107.         PendingIntent contentIntent = PendingIntent.getActivity(this0new Intent(), 0);  
  108.         notification.setLatestEventInfo(getApplicationContext(), "My notification""Hello World!", contentIntent);  
  109.         notificationManager.notify(1, notification);  
  110.     }  
  111.   
  112.     @LongClick  
  113.     void startExtraActivity() {  
  114.         Intent intent = new Intent(this, ActivityWithExtra_.class);  
  115.   
  116.         intent.putExtra(ActivityWithExtra.MY_DATE_EXTRA, new Date());  
  117.         intent.putExtra(ActivityWithExtra.MY_STRING_EXTRA, "hello !");  
  118.         intent.putExtra(ActivityWithExtra.MY_INT_EXTRA, 42);  
  119.   
  120.         startActivity(intent);  
  121.     }  
  122.   
  123.     @Click  
  124.     void startListActivity(View v) {  
  125.         startActivity(new Intent(this, MyListActivity_.class));  
  126.     }  
  127.   
  128.     @Touch  
  129.     void myTextView(MotionEvent event) {  
  130.         Log.d("MyActivity""myTextView was touched!");  
  131.     }  
  132.   
  133.     @Transactional  
  134.     int transactionalMethod(SQLiteDatabase db, int someParam) {  
  135.         return 42;  
  136.     }  
  137.   
  138. }  

这个项目的好处是使用到了IOC模式,代码量小而且简洁,使程序员更多的关注于业务逻辑而不是页面,而且@Backgroud这个标签下开启的线程在线程池中管理。
类似的项目还有Android Binding,RoboGuice等,有兴趣可以看一下这个文章
CLEAN CODE IN ANDROID APPLICATIONS一个Spring gay写得,很不错哦~
http://blog.springsource.com/2011/08/26/clean-code-with-android/

 

本文标签

除非注明,文章均为( noway )原创,转载请保留链接: http://blog-old.z3a105.com/?p=141

使用框架编写Android程序:等您坐沙发呢!

发表评论





       ==QQ:122320466==

 微信    QQ群


0

Aujourd’hui, une partie avec le développement du e-commerce, achats en ligne est devenu une partie de la vie pour beaucoup de gens. La mariage a commencé achats en ligne. Si vous choisissez achats les mariages en ligne, il peut être beaucoup moins cher que le salon de la Robe de mariée pas chermariée local, réduisant le budget de mariage. vous pouvez avoir beaucoup de choix si acheter de mariage en ligne. vous pouvez ramasser une robe de mariée bon marché sur Internet.
Piercing fascinerande figur, och nu tittar vi på 2016 senast brudklänning, kan du vara den vackraste bruden det!2016 senaste Bra brudklänning, söt temperament Bra design, romantiska spetsar blomma kjol, som du lägger till en elegant och charmig temperament.Kvinnan tillbaka mjuka linjer, människor brudklänningofta få en känsla av oändlig frestelse. Fall 2016 mässan, lämnar uppgifter om ditt bröllop charmig.
Yesterday afternoon, the Chinese team was training in the Guangzhou Gymnasium, when the reporter asked Zhao Yunlei the feeling of wearing the new cheap jersey , cheap jerseys online shopshe readily took a shirt from the bag crumpled ball to reporters, and she said with a smile: ” This shirt is light. ”Zhao Yunlei said: “Our material is very light like with the clothes of the tennis King Nadal, Federer, after the sweat, sweat does not drip down to the ground, when we do move, it is easy pace slipping if the sweat drip on the floor.”Tennis players Zhang Yawen, told reporters: “You might think the clothes attached to the body, fearing we swing will be affected, in fact, we do not feel anything, because the clothes are very light, very soft, put on quite comfortable. And it’s particularly good clothes to dry, washing and will dry in 15 minutes. ”
China’s sports enthusiasts NFL sweatshirt with mad love and the pursuit of, and therefore, NFL jerseys have a good market in China and development. China is a populous country, is the consumer, the economic momentum is so good, the sales prospects sportswear is immeasurable. With hot sales sweatshirt, but also to promote the importance of sports fans, on health, on the other hand is a matter of concern for the World Cup, fans wearing NFL jerseys and also can express themselves more fully love and obsession Therefore, NFL jerseys Wholesale jerseys online shopwholesale has good prospects and development in China.
ANTA-ANTA Sports Products Limited, referred to as ANTA Sports, Anta, is China’s leading sporting goods companies, mainly engaged in the design, development, manufacture and marketing of ANTA brand sporting goods, including sports footwear, apparel and accessories. Anta sweatshirt design advantages, warm stretch knit fabric, using Slim version of model, more personal fit, bid farewell to bloated, so wearing more stylish.GUIRENNIAO-This logo is a spiritual totem, smooth graphics implication unstoppable force; flexible deliver an elegant arc Wholesale jerseys china shop movement, strength and speed of the United States, a symbol of passion and rationality publicity “Heart” and “meaning”, “concept” unity; pass the fearless and enterprising mind, showing beyond the realm of self, to unstoppable force to create the future.XTEP-Xtep (China) Co., Ltd. is a comprehensive development wholesale jerseys china shop, production and marketing of Xtep brand (XTEP) sports shoes, clothing, bags, caps, balls, socks mainly large sporting goods industry enterprises.
There are a lot of fans in identifying the authenticity of the above cheap jerseys have great distress, so here to i will show you some methods to definitely affordable inexpensive cheap jerseys : Firstly, we should look at if it is working fine. China has been called the world’s factory, a lot cheap jerseys factories in China have foundries, but our cheap jerseys are all from here! Secondly, should to see whether it is the , we all know that it is difficult to get out of print once a genuine cheap cheap jerseys free shipping jersey was print. and we have all kind of stocka on the whole website, in other words, we have all you want ! Finally, look at the price, our price is not necessarily the lowest in the whole website but it must be most fair on the whole website, we certainly you will not regret later when you buy it. Of course, except that cheap jerseys, we also have the other products, such as socks, leggings and some other related products, everyone can enjoy the best services of here!

KUBET