I am trying to make a custom menuitem but trying to get a property from the custom class gives mejava.lang.NullPointerException
this is my code:
activity_main.xml
<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="@layout/nav_header_main"
app:menu="@menu/main.xml" />
main.xml
<menu>
<item
android:id="@+id/nav_newversion"
tools:ignore="MenuTitle"
app:actionViewClass="com.package.meteorocorte.customitem" />
</menu>
customitem.java
public class customitem extends LinearLayout {
TextView text=new TextView(getContext());
public customitem(Context context) {
super(context);
setOrientation(VERTICAL);
setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
setBackgroundColor(Color.GREEN);
setPadding(0,12,0,12);
text.setText(("hola"));
text.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
text.setTextColor(Color.BLACK);
addView(text);
}
public TextView getText() {
return text;
}
}
MainActivity.java
MenuItem item=((NavigationView)findViewById(R.id.nav_view)).getMenu().getItem(0);
item.setVisible(true);
TextView text= ((customitem) item.getActionView()).getText();//aqui me da java.lang.NullPointerException
And if you were wondering if customization would work, I leave you the image:
Most of what you do is correct, you get the element from the
NavigationView
, this should work without problem:But it is super important that in the menu file
main.xml
the element is actually the first (index 0)and the class
customitem
is actually in the package: "com.package.meteorocorte", ensure these two things and I assure you that you will do what you want without any problem.