3

我有带有列表导航的 ActionBar。如我所见,仅对新选择的位置调用 ActionBar.OnNavigationListener 。即使我选择了已经选择的项目,有没有办法为每个选择进行回调?

4

1 回答 1

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;
}
于 2013-03-13T01:20:05.830 回答