I cant solve this simple problem.
i have Main activity,it has a toolbar and a fragment.
Main Activity xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.dimfcompany.macapp2.MainActivity">
<android.support.v7.widget.Toolbar
android:id="@+id/toolBarTest"
android:titleTextColor="@color/macYellow"
android:title="dsfsdf"
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="@color/macRed">
</android.support.v7.widget.Toolbar>
<fragment
android:id="@+id/testfrag"
android:name="com.dimfcompany.macapp2.fragtest1"
android:layout_width="match_parent"
android:layout_height="match_parent"
></fragment>
</LinearLayout>
MainActivity Java
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar=(Toolbar)findViewById(R.id.toolBarTest);
toolbar.setTitle("BLDFLDSF");
}
public void setToolBarText(String text)
{
toolbar.setTitle("dsfsdfsdf");
}
}
Setting title in MainActivity.java onCreateMethod works.
Then i want my title to change if fragment content changes.
In my fragment I have the onViewCreated() method and I'm trying to change the title from this method.
public void onViewCreated(View view, @Nullable Bundle savedInstanceState)
{
((MainActivity)getActivity()).setToolBarText("FragmentTitle");
toolbar=(Toolbar) view.findViewById(R.id.toolBarTest);
toolbar.setTitle("FragmentTitle");
}
I tried changing it directly and changing with calling method setToolBarText in MainActivity.
I always have an exception
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.Toolbar.setTitle(java.lang.CharSequence)' on a null object reference
What i am doing wrong?