Android 最火的快速开发框架AndroidAnnotations使用详解

来源:互联网 发布:windows连不上无线网 编辑:程序博客网 时间:2024/05/14 13:33

Android 最火的快速开发框架androidannotations配置详解文章中有eclipse配置步骤,Android 最火快速开发框架AndroidAnnotations简介文章中的简单介绍,本篇注重讲解AndroidAnnotations中注解方法的使用。

@EActivity

示例:

?
1
2
3
4
@EActivity(R.layout.main)
public class MyActivity extendsActivity {
 
}
@fragment

示例:

?
1
2
3
<pre class="brush:java;">@EFragment(R.layout.my_fragment_layout)
public class MyFragment extendsFragment {
}</pre>
注册:
?
1
<fragment android:id="@+id/myFragment"android:name="com.company.MyFragment_"android:layout_width="fill_parent"android:layout_height="fill_parent"></fragment>

创建:

?
1
MyFragment fragment =new MyFragment_();

普通类:

?
1
2
3
4
@EBean
public class MyClass {
 
}


注意:这个类必须仅仅只能有一个构造函数,参数最多有一个context。

Activity中使用:

?
1
2
3
4
5
6
7
@EActivity
public class MyActivity extendsActivity {
 
  @Bean
  MyOtherClass myOtherClass;
 
}

也可以用来声明接口:

?
1
2
@Bean(MyImplementation.class)
    MyInterface myInterface;

在普通类中还可以注入根环境:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@EBean
public class MyClass {
 
  @RootContext
  Context context;
 
  // Only injected if the root context is an activity
  @RootContext
  Activity activity;
 
  // Only injected if the root context is a service
  @RootContext
  Service service;
 
  // Only injected if the root context is an instance of MyActivity
  @RootContext
  MyActivity myActivity;
 
}

如果想在类创建时期做一些操作可以:

?
1
2
3
4
@AfterInject
  publicvoid doSomethingAfterInjection() {
    // notificationManager and dependency are set
  }

单例类需要如下声明:

?
1
2
3
4
@EBean(scope = Scope.Singleton)
public class MySingleton {
 
}

注意:在单例类里面不可以注入view和事件绑定,因为单例的生命周期比Activity和Service的要长,以免发生内存溢出。

@EView

?
1
2
3
4
5
6
7
8
9
10
11
12
13
@EView
public class CustomButton extendsButton {
 
        @App
        MyApplication application;
 
        @StringRes
        String someStringResource;
 
    publicCustomButton(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
}


注册:

?
1
<com.androidannotations.view.custombutton_ android:layout_width="match_parent"android:layout_height="wrap_content"></com.androidannotations.view.custombutton_>

创建:

?
1
CustomButton button = CustomButton_.build(context);


@EViewGroup

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@EViewGroup(R.layout.title_with_subtitle)
public class TitleWithSubtitle extendsRelativeLayout {
 
    @ViewById
    protectedTextView title, subtitle;
 
    publicTitleWithSubtitle(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
 
    publicvoid setTexts(String titleText, String subTitleText) {
        title.setText(titleText);
        subtitle.setText(subTitleText);
    }
 
}

注册:

?
1
<com.androidannotations.viewgroup.titlewithsubtitle_ android:id="@+id/firstTitle"android:layout_width="match_parent"android:layout_height="wrap_content"></com.androidannotations.viewgroup.titlewithsubtitle_>

@EApplication

?
1
2
3
4
@EApplication
public class MyApplication extendsApplication {
 
}

Activity中使用:
?
1
2
3
4
5
6
7
@EActivity
public class MyActivity extendsActivity {
 
  @App
  MyApplication application;
 
}

@EService
?
1
2
3
4
@EService
public class MyService extendsService {
 
}

跳转service:
?
1
MyService_.intent(getApplication()).start();

停止service:
?
1
MyService_.intent(getApplication()).stop();

@EReceiver
?
1
2
3
4
@EReceiver
public class MyReceiver extendsBroadcastReceiver {
 
}

@Receiver可以替代声明BroadcastReceiver
?
1
2
3
4
5
6
7
8
9
@EActivity
public class MyActivity extendsActivity {
 
  @Receiver(actions ="org.androidannotations.ACTION_1")
  protectedvoid onAction1() {
 
  }
 
}

@EProvider
?
1
2
3
4
@EProvider
public class MyContentProvider extendsContentProvider {
 
}

@ViewById
?
1
2
3
4
5
6
7
8
9
10
@EActivity
public class MyActivity extendsActivity {
 
  // Injects R.id.myEditText,变量名称必须和布局的id名称一致
  @ViewById
  EditText myEditText;
 
  @ViewById(R.id.myTextView)
  TextView textView;
}

@AfterViews
?
1
2
3
4
5
6
7
8
@EActivity(R.layout.main)
public class MyActivity extendsActivity {
 
    @ViewById
    TextView myTextView;
 
    @AfterViews
    voidupdateTextWithDate() {<pre class="brush:java;">//一定要在这里进行view的一些设置,不要在oncreate()中设置,因为oncreate()在执行时 view还没有注入</pre>        myTextView.setText("Date: " + new Date());    }[...]

@StringRes
?
1
2
3
4
5
6
7
8
9
10
@EActivity
public class MyActivity extendsActivity {
 
  @StringRes(R.string.hello)
  String myHelloString;//不能设置成私有变量
 
  @StringRes
  String hello;
 
}

@ColorRes
?
1
2
3
4
5
6
7
8
9
10
@EActivity
public class MyActivity extendsActivity {
 
  @ColorRes(R.color.backgroundColor)
  intsomeColor;
 
  @ColorRes
  intbackgroundColor;
 
}

@AnimationRes
?
1
2
3
4
5
6
7
8
9
10
@EActivity
public class MyActivity extendsActivity {
 
  @AnimationRes(R.anim.fadein)
  XmlResourceParser xmlResAnim;
 
  @AnimationRes
  Animation fadein;
 
}

@DimensionRes
?
1
2
3
4
5
6
7
8
9
10
@EActivity
public class MyActivity extendsActivity {
 
  @DimensionRes(R.dimen.fontsize)
  floatfontSizeDimension;
 
  @DimensionRes
  floatfontsize;
 
}

@DImensionPixelOffsetRes
?
1
2
3
4
5
6
7
8
9
10
@EActivity
public class MyActivity extendsActivity {
 
  @DimensionPixelOffsetRes(R.string.fontsize)
  intfontSizeDimension;
 
  @DimensionPixelOffsetRes
  intfontsize;
 
}

@DimensionPixelSizeRes
?
1
2
3
4
5
6
7
8
9
10
@EActivity
public class MyActivity extendsActivity {
 
  @DimensionPixelSizeRes(R.string.fontsize)
  intfontSizeDimension;
 
  @DimensionPixelSizeRes
  intfontsize;
 
}

其他的Res:
  • @BooleanRes
  • @ColorStateListRes
  • @DrawableRes
  • @IntArrayRes
  • @IntegerRes
  • @LayoutRes
  • @MovieRes
  • @TextRes
  • @TextArrayRes
  • @StringArrayRes
    @Extra
    ?
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    @EActivity
    public class MyActivity extendsActivity {
     
      @Extra("myStringExtra")
      String myMessage;
     
      @Extra("myDateExtra")
      Date myDateExtraWithDefaultValue =new Date();
     
    }

    或者:
    ?
    1
    2
    3
    4
    5
    6
    7
    @EActivity
    public class MyActivity extendsActivity {
     
      // The name of the extra will be "myMessage",名字必须一致
      @Extra
      String myMessage;
    }

    传值:
    ?
    1
    MyActivity_.intent().myMessage("hello").start() ;

    @SystemService
    ?
    1
    2
    3
    4
    5
    6
    @EActivity
    public class MyActivity extendsActivity {//
      @SystemService
      NotificationManager notificationManager;
     
    }

    @HtmlRes
    ?
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    @EActivity
    public class MyActivity extendsActivity {
     
      // Injects R.string.hello_html
      @HtmlRes(R.string.hello_html)
      Spanned myHelloString;
     
      // Also injects R.string.hello_html
      @HtmlRes
      CharSequence helloHtml;
     
    }

    @FromHtml
    ?
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    @EActivity
    public class MyActivity extendsActivity {//必须用在TextView
     
      @ViewById(R.id.my_text_view)
      @FromHtml(R.string.hello_html)
      TextView textView;
     
      // Injects R.string.hello_html into the R.id.hello_html view
      @ViewById
      @FromHtml
      TextView helloHtml;
     
    }

    @NonConfigurationInstance
    ?
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    public class MyActivity extendsActivity {//等同于 Activity.onRetainNonConfigurationInstance()
     
      @NonConfigurationInstance
      Bitmap someBitmap;
     
      @NonConfigurationInstance
      @Bean
      MyBackgroundTask myBackgroundTask;
     
    }

    @HttpsClient
    ?
    1
    2
    <pre class="brush:java;">@HttpsClient
    HttpClient httpsClient;</pre>

    示例:
    ?
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    @EActivity
    public class MyActivity extendsActivity {
     
        @HttpsClient(trustStore=R.raw.cacerts,
            trustStorePwd="changeit",
            hostnameVerif=true)
        HttpClient httpsClient;
     
        @AfterInject
        @Background
        publicvoid securedRequest() {
            try{
                HttpGet httpget =new HttpGet("https://www.verisign.com/");
                HttpResponse response = httpsClient.execute(httpget);
                doSomethingWithResponse(response);
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
     
        @UiThread
        publicvoid doSomethingWithResponse(HttpResponse resp) {
            Toast.makeText(this,"HTTP status " + resp.getStatusLine().getStatusCode(), Toast.LENGTH_LONG).show();
        }
    }

    @FragmentArg
    ?
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    @EFragment
    public class MyFragment extendsFragment {//等同于 Fragment Argument
     
      @FragmentArg("myStringArgument")
      String myMessage;
     
      @FragmentArg
      String anotherStringArgument;
     
      @FragmentArg("myDateExtra")
      Date myDateArgumentWithDefaultValue =new Date();
     
    }
    ?
    1
    2
    3
    4
    MyFragment myFragment = MyFragment_.builder()
      .myMessage("Hello")
      .anotherStringArgument("World")
      .build();

    @Click
    ?
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    @Click(R.id.myButton)
    void myButtonWasClicked() {
        [...]
    }
    @Click
    void anotherButton() {//如果不指定则函数名和id对应
        [...]
    }
    @Click
    void yetAnotherButton(View clickedView) {
        [...]
    }

    其他点击事件:
    • Clicks with @Click
    • Long clicks with @LongClick
    • Touches with @Touch

      AdapterViewEvents

      • Item clicks with @ItemClick
      • Long item clicks with @ItemLongClick
      • Item selection with @ItemSelect有两种方式调用:1.
        ?
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        @EActivity(R.layout.my_list)
        public class MyListActivity extendsActivity {
         
            // ...
         
            @ItemClick
            publicvoid myListItemClicked(MyItem clickedItem) {//MyItem是adapter的实体类,等同于adapter.getItem(position)
         
            }
         
            @ItemLongClick
            publicvoid myListItemLongClicked(MyItem clickedItem) {
         
            }
         
            @ItemSelect
            publicvoid myListItemSelected(booleanselected, MyItem selectedItem) {
         
            }
         
        }

        2.
        ?
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        @EActivity(R.layout.my_list)
        public class MyListActivity extendsActivity {
         
            // ...
         
            @ItemClick
            publicvoid myListItemClicked(intposition) {//位置id
         
            }
         
            @ItemLongClick
            publicvoid myListItemLongClicked(intposition) {
         
            }
         
            @ItemSelect
            publicvoid myListItemSelected(booleanselected, int position) {
         
            }
         
        }

        @SeekBarProgressChange
        ?
        1
        <pre class="brush:java;">//等同于SeekBar.OnSeekBarChangeListener.onProgressChanged(SeekBar, int, boolean)</pre>
        ?
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        @SeekBarProgressChange(R.id.seekBar)
         voidonProgressChangeOnSeekBar(SeekBar seekBar, intprogress, booleanfromUser) {
            // Something Here
         }
         
         @SeekBarProgressChange(R.id.seekBar)
         voidonProgressChangeOnSeekBar(SeekBar seekBar, intprogress) {
            // Something Here
         }
         
         @SeekBarProgressChange({R.id.seekBar1, R.id.seekBar2})
         voidonProgressChangeOnSeekBar(SeekBar seekBar) {
            // Something Here
         }
         
         @SeekBarProgressChange({R.id.seekBar1, R.id.seekBar2})
         voidonProgressChangeOnSeekBar() {
            // Something Here
         }@SeekBarTouchStartand @SeekBarTouchStop

        @SeekBarTouchStart 和 @SeekBarTouchStop接受开始和结束事件的监听
        @TextChange
        ?
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        @TextChange(R.id.helloTextView)
         voidonTextChangesOnHelloTextView(CharSequence text, TextView hello,int before, int start, intcount) {
            // Something Here
         }
         
         @TextChange
         voidhelloTextViewTextChanged(TextView hello) {
            // Something Here
         }
         
         @TextChange({R.id.editText, R.id.helloTextView})
         voidonTextChangesOnSomeTextViews(TextView tv, CharSequence text) {
            // Something Here
         }
         
         @TextChange(R.id.helloTextView)
         voidonTextChangesOnHelloTextView() {
            // Something Here
         }

        @BeforeTextChange
        ?
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        @BeforeTextChange(R.id.helloTextView)
         voidbeforeTextChangedOnHelloTextView(TextView hello, CharSequence text,int start, int count, intafter) {
            // Something Here
         }
         
         @BeforeTextChange
         voidhelloTextViewBeforeTextChanged(TextView hello) {
            // Something Here
         }
         
         @BeforeTextChange({R.id.editText, R.id.helloTextView})
         voidbeforeTextChangedOnSomeTextViews(TextView tv, CharSequence text) {
            // Something Here
         }
         
         @BeforeTextChange(R.id.helloTextView)
         voidbeforeTextChangedOnHelloTextView() {
            // Something Here
         }

        @AfterTextChange
        ?
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        @AfterTextChange(R.id.helloTextView)
         voidafterTextChangedOnHelloTextView(Editable text, TextView hello) {
            // Something Here
         }
         
         @AfterTextChange
         voidhelloTextViewAfterTextChanged(TextView hello) {
            // Something Here
         }
         
         @AfterTextChange({R.id.editText, R.id.helloTextView})
         voidafterTextChangedOnSomeTextViews(TextView tv, Editable text) {
            // Something Here
         }
         
         @AfterTextChange(R.id.helloTextView)
         voidafterTextChangedOnHelloTextView() {
            // Something Here
         }

        @OptionsMenu和OptionsItem
        ?
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
        24
        25
        26
        27
        28
        29
        30
        31
        32
        33
        34
        35
        36
        @EActivity
        @OptionsMenu(R.menu.my_menu)
        public class MyActivity extendsActivity {
         
            @OptionMenuItem
            MenuItem menuSearch;
         
            @OptionsItem(R.id.menuShare)
                voidmyMethod() {
                  // You can specify the ID in the annotation, or use the naming convention
                }
         
            @OptionsItem
            voidhomeSelected() {
              // home was selected in the action bar
                  // The "Selected" keyword is optional
            }
         
            @OptionsItem
            booleanmenuSearch() {
                  menuSearch.setVisible(false);
                  // menuSearch was selected
                  // the return type may be void or boolean (false to allow normal menu processing to proceed, true to consume it here)
                  returntrue;
            }
         
            @OptionsItem({ R.id.menu_search, R.id.menu_delete })
            voidmultipleMenuItems() {
              // You can specify multiple menu item IDs in @OptionsItem
            }
         
            @OptionsItem
            voidmenu_add(MenuItem item) {
              // You can add a MenuItem parameter to access it
            }
        }

        或者:
        ?
        1
        2
        3
        4
        5
        @EActivity
        @OptionsMenu({R.menu.my_menu1, R.menu.my_menu2})
        public class MyActivity extendsActivity {
         
        }

        @Background执行:
        ?
        1
        2
        3
        4
        5
        6
        7
        8
        void myMethod() {
            someBackgroundWork("hello",42);
        }
         
        @Background
        void someBackgroundWork(String aParam, long anotherParam) {
            [...]
        }

        取消:
        ?
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        void myMethod() {
            someCancellableBackground("hello",42);
            [...]
            booleanmayInterruptIfRunning = true;
            BackgroundExecutor.cancelAll("cancellable_task", mayInterruptIfRunning);
        }
         
        @Background(id="cancellable_task")
        void someCancellableBackground(String aParam, longanotherParam) {
            [...]
        }

        非并发执行:
        ?
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        void myMethod() {
            for(int i = 0; i < 10; i++)
                someSequentialBackgroundMethod(i);
        }
         
        @Background(serial ="test")
        void someSequentialBackgroundMethod(int i) {
            SystemClock.sleep(newRandom().nextInt(2000)+1000);
            Log.d("AA","value : " + i);
        }

        延迟:
        ?
        1
        2
        3
        @Background(delay=2000)
        void doInBackgroundAfterTwoSeconds() {
        }

        @UiThreadUI线程:
        ?
        1
        2
        3
        4
        5
        6
        7
        8
        void myMethod() {
            doInUiThread("hello",42);
        }
         
        @UiThread
        void doInUiThread(String aParam, long anotherParam) {
            [...]
        }

        延迟:
        ?
        1
        2
        3
        @UiThread(delay=2000)
        void doInUiThreadAfterTwoSeconds() {
        }

        优化UI线程:
        ?
        1
        2
        3
        @UiThread(propagation = Propagation.REUSE)
        void runInSameThreadIfOnUiThread() {
        }

        进度值改变:
        ?
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        @EActivity
        public class MyActivity extendsActivity {
         
          @Background
          voiddoSomeStuffInBackground() {
            publishProgress(0);
            // Do some stuff
            publishProgress(10);
            // Do some stuff
            publishProgress(100);
          }
         
          @UiThread
          voidpublishProgress(intprogress) {
            // Update progress views
          }
         
        }

        @OnActivityResult
        ?
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        @OnActivityResult(REQUEST_CODE)
         voidonResult(int resultCode, Intent data) {
         }
         
         @OnActivityResult(REQUEST_CODE)
         voidonResult(int resultCode) {
         }
         
         @OnActivityResult(ANOTHER_REQUEST_CODE)
         voidonResult(Intent data) {
         }
         
         @OnActivityResult(ANOTHER_REQUEST_CODE)
         voidonResult() {
         }

        以上的注释用法基本包含了平常程序中的事件绑定,用AndroidAnnotations框架可以专注于做逻辑开发,最主要是简化代码编写,容易维护。如有问题可以参考官方文档https://github.com/excilys/androidannotations/wiki/Cookbook,或者留言。转载务必注明出处。
0 0
原创粉丝点击