AndroidAnnotations: how to access View on @ItemCli

2019-09-17 02:17发布

问题:

I use AndroidAnnotations to build Android application. But I have no idea how to refactor this below to use @ItemClick because @ItemClick doesn't accept View parameter. By the way, I use View to get tag of selected GridView.

gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
       @Override
       public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
           String url = (String) view.getTag();
           intents.put("image", url);

           DetailActivity_.launch(HomeActivity.this, view.findViewById(R.id.image), intents);
       }
 });

Any idea?

回答1:

Unfortunately you cannot add a View parameter, but you can use the position parameter. The problem with that there is no method to return the clicked View, so you have to use some logic to get the View from all the children.

@ViewById(R.id.gridViewId)
GridView gridView;

@ItemClick(R.id.gridViewId)
void itemClicked(int position) {
    int firstPosition = gridView.getFirstVisiblePosition();
    int lastPosition = gridView.getLastVisiblePosition();

    View clickedView;

    if ((position < firstPosition) || (position > lastPosition))
        clickedView = null;

    clickedView = gridView.getChildAt(position - firstPosition);
    // do sg with clicked view
}

But this is actually not as clean as your code without AA... However, the View parameter may be supported soon. Until that, i suggest to stick with the old way if you really has to work with the View param.



回答2:

You can't retrieve the View with @ItemClick annotation, but the selected item itself.

@ItemClick(R.id.yourgrid_id)
void itemClicked(Object item) {

//DO SOMETHING
}

item type depends on your Grid adapter.