Search code examples
androiduser-interfaceandroid-toolbar

How can I use icon on custom tool bar when I include it on another activity?


I am including toolbar on my followup activity after adding I want to add an icon on right side but it give error.Please help me how can I resolve it.

public class Add_Followup extends AppCompatActivity {

androidx.appcompat.widget.Toolbar tool_bar

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

    tool_bar=(Toolbar) findViewById(R.id.custom_toolbar);
    setSupportActionBar(tool_bar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    tool_bar.setNavigationIcon(R.drawable.back);
  }

I include like this.

<include
    layout="@layout/custom_tool_bar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

This is customlayout

<androidx.appcompat.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:fontFamily="serif"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="#FF9B9B"
android:elevation="4dp"
app:title="Welcome"
app:titleTextColor="#ffff"
app:subtitleTextColor="#ffff"
android:id="@+id/custom_toolbar">

I am facing this exception

  Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.appcompat.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
    at com.example.loginproject.Add_Followup.onCreate(Add_Followup.java:54)
    at android.app.Activity.performCreate(Activity.java:7802)
    at android.app.Activity.performCreate(Activity.java:7791)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245)

Solution

  • Just call id like this.

    <include layout="@layout/custom_tool_bar"
        android:id="@+id/custom_toolbar"/>