在android片段中设置标题工具栏,给出空指针

时间:2017-08-08 18:39:44

标签: android android-layout swiperefreshlayout

我想在android片段中设置工具栏标题。但我的代码在下面的代码中给出了空指针异常:

((AppCompatActivity)getActivity()).getSupportActionBar().setTitle("PROFIL");

这是我的完整代码

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() {
    }
}

任何建议将不胜感激。谢谢

1 个答案:

答案 0 :(得分:1)

将以下代码从onCreateView()方法移至onActivityCreated()方法。

    toolbar = (Toolbar) rootView.findViewById(R.id.toolbar);
    ((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
    ((AppCompatActivity)getActivity()).getSupportActionBar().setTitle("PROFIL");

只有在onActivityCreated()之后,才能确定Activity返回了getActivity()

getView()内使用rootView代替onActivityCreated()