[英]set title toolbar in android fragment giving null pointer
i want to set toolbar title in android fragment. 我想在Android片段中设置工具栏标题。 but my code giving null pointer exception in below code:
但是我的代码在下面的代码中给出了空指针异常:
((AppCompatActivity)getActivity()).getSupportActionBar().setTitle("PROFIL");
this is my full code 这是我的完整代码
package id.prasetyo.appsgaul.Layout;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import id.prasetyo.appsgaul.R;
public class Profil2Activity extends android.support.v4.app.Fragment implements SwipeRefreshLayout.OnRefreshListener {
private Toolbar toolbar;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_profil2, container, false);
toolbar = (Toolbar) rootView.findViewById(R.id.toolbar);
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar
((AppCompatActivity)getActivity()).getSupportActionBar().setTitle( "PROFIL");
return rootView;
}
@Override
public void onRefresh() {
}
}
any suggestion would be appreciated. 任何建议将不胜感激。 thank you
谢谢
Move the below code from onCreateView()
method to onActivityCreated()
method. 将下面的代码从
onCreateView()
方法移动到onActivityCreated()
方法。
toolbar = (Toolbar) rootView.findViewById(R.id.toolbar);
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
((AppCompatActivity)getActivity()).getSupportActionBar().setTitle("PROFIL");
Only after the onActivityCreated()
you can be sure that there is an Activity
returned from getActivity()
. 只有在
onActivityCreated()
之后,才能确保从getActivity()
返回了一个Activity
。
And use getView()
instead of rootView
inside onActivityCreated()
. 并在
onActivityCreated()
使用getView()
而不是rootView
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.