如何将onItemSelectedListener附加到WearableNavigationDrawerView?

时间:2018-11-09 09:47:19

标签: android wear-os

我已经实现了NavigationDrawer,但是在NavigationAdapter中,onItemSelected方法未运行。我猜想缺少将侦听器附加到某个地方的功能。我认为MainActivity类具有各个组成部分,只是无法弄清楚在何处以及如何添加onItemSelectedListener。

public class MainActivity extends WearableActivity {

    private WearableNavigationDrawerView mWearableNavigationDrawer;
    private static final SectionFragment.Section DEFAULT_SECTION = SectionFragment.Section.Main;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        setAmbientEnabled();

        mWearableNavigationDrawer = (WearableNavigationDrawerView) findViewById(R.id.top_navigation_drawer);
        mWearableNavigationDrawer.setAdapter(new NavigationAdapter(this));
        mWearableNavigationDrawer.getController().peekDrawer();
    }

    private final class NavigationAdapter
            extends WearableNavigationDrawerView.WearableNavigationDrawerAdapter implements WearableNavigationDrawerView.OnItemSelectedListener {

        private final Context mContext;
        private SectionFragment.Section mCurrentSection = DEFAULT_SECTION;

        NavigationAdapter(final Context context) {
            mContext = context;
        }

        @Override
        public String getItemText(int index) {
            return mContext.getString(SectionFragment.Section.values()[index].titleRes);
        }

        @Override
        public Drawable getItemDrawable(int index) {
            return mContext.getDrawable(SectionFragment.Section.values()[index].drawableRes);
        }

        @Override
        public void onItemSelected(int pos) {
            SectionFragment.Section selectedSection = SectionFragment.Section.values()[pos];

            // Only replace the fragment if the section is changing.
            if (selectedSection == SectionFragment.Section.Main) {
                setContentView(R.layout.activity_main);
            } else {
                setContentView(R.layout.activity_alarm);
            }

            mCurrentSection = selectedSection;
        }

        @Override
        public int getCount() {
            return SectionFragment.Section.values().length;
        }
    }
} 

1 个答案:

答案 0 :(得分:0)

在方法onCreate()中,您不仅要将类NavigationAdapter的实例传递给setAdapter()的方法mWearableNavigationDrawer,而且还传递给方法addOnItemSelectedListener()mWearableNavigationDrawer

  NavigationAdapter myAdapter = new NavigationAdapter(this)
  mWearableNavigationDrawer.setAdapter(myAdapter);
  mWearableNavigationDrawer.addOnItemSelectedListener(myAdapter);