setVisibility在DrawerNavigation中不起作用

时间:2017-08-05 07:06:50

标签: android

我在抽屉中使用NavigationView并且Menu中有一个项目app:actionLayout属性指向包含LinearLayout的{​​{1}},并且TextView具有属性TextView。我希望在点击android:visibility="invisible"中的textview时可以看到此item。但是它没有用,我添加了一个Menu来检查点击监听器是否正常工作,并且发现点击监听器正在工作,但Toast不可见。

enter image description here

点击监听器(活动布局名称为:textView):

main_activity.xml

以下是navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { switch (item.getItemId()){ case R.id.nav_kitchen_key: View kitchenKeyLayout = getLayoutInflater().inflate(R.layout.nav_kitchen_key, null); TextView kitchenKeyTextView = (TextView)kitchenKeyLayout.findViewById(R.id.show_kitchen_key); kitchenKeyTextView.setVisibility(View.VISIBLE); break; } return true; } });

Menu item

指向<item android:id="@+id/nav_kitchen_key" android:title="Kitchen Key" android:icon="@drawable/if_key" app:actionLayout="@layout/nav_kitchen_key" /> 的菜单项app:actionLayout的属性,此处为nav_kitchen_key.xml

nav_kitchen_key.xml

2 个答案:

答案 0 :(得分:3)

您不应该创建新的视图,您应该从MenuItem,MenuItem.getActionView()

获取
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()){
                    case R.id.nav_kitchen_key:
                        LinearLayout kitchenKeyLayout = (LinearLayout) item.getActionView();

                        TextView kitchenKeyTextView = (TextView)kitchenKeyLayout.findViewById(R.id.show_kitchen_key);
                        kitchenKeyTextView.setVisibility(View.VISIBLE);
                        break;
                }
                return true;
            }
        });

答案 1 :(得分:1)

您可以从getActionView

获取视图
LinearLayout kitchenKeyLayout = (LinearLayout) item.getActionView();
    // This returns the container layout  

TextView kitchenKeyTextView = (TextView)kitchenKeyLayout.findViewById(R.id.show_kitchen_key);
                            kitchenKeyTextView.setVisibility(View.VISIBLE);

kitchenKeyTextView.setVisibility(View.VISIBLE);