我有带列表导航的ActionBar。 正如我所看到的,仅为新选择的位置调用ActionBar.OnNavigationListener。 有没有办法让每个选项都有回调,即使我选择了已选择的项目?
答案 0 :(得分:2)
我只有一个hacky解决方案,我愿意接受如何改进它的建议。但它的确有效。
诀窍是在实际选择之后有一个不可见的项目被选中。这样,当您重新选择所选项时,会再次调用onNavigationItemSelected
。
public class ReselectAdapter extends ArrayAdapter<String> {
private Context mContext;
private ArrayList<String> mItems;
private int mInternalPosition;
public ReselectAdapter(Context context, ArrayList<String> items) {
super(context, R.layout.sherlock_spinner_item, items);
mContext = context;
mItems = items;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView textView = (TextView) convertView;
if (textView == null) {
textView = (TextView) LayoutInflater.from(mContext).inflate(
R.layout.sherlock_spinner_item, null);
textView.setText(mItems.get(mInternalPosition));
}
return textView;
}
@Override
public View getDropDownView(int position, View convertView, ViewGroup
parent) {
TextView textView = null;
if (position == mItems.size() - 1) {
textView = new TextView(mContext);
textView.setHeight(0);
} else {
textView = (TextView) LayoutInflater.from(mContext)
.inflate(R.layout.sherlock_spinner_dropdown_item,
parent, false);
textView.setText(mItems.get(position));
}
parent.setVerticalScrollBarEnabled(false);
return textView;
}
public void setInternalPosition(int internalPosition) {
mInternalPosition = internalPosition;
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
// [...]
ArrayList<String> items = new ArrayList<String>();
items.add("A");
items.add("B");
items.add("C");
items.add(""); // the last item is the invisible one
mReselectAdapter = new ReselectAdapter(context, items);
getSupportActionBar().setListNavigationCallbacks(mReselectAdapter, this);
}
@Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
int navigationItemCount = getSupportActionBar().getNavigationItemCount();
if (itemPosition == navigationItemCount - 1) {
return true;
}
Log.i("onNavigationItemSelected", mReselectAdapter.getItem(itemPosition));
mReselectAdapter.setInternalPosition(itemPosition);
getSupportActionBar().setSelectedNavigationItem(navigationItemCount - 1);
return true;
}