Android Fragment Null指针异常

时间:2017-04-23 04:27:22

标签: android android-fragments nullpointerexception android-fragmentactivity

我正在学习android开发(新手)。我想用textview将一个片段添加到mainActivity并更改文本。这段代码完美无缺:

public class Fragment1 extends Fragment {
//@Nullable
//@Override
TextView textt;
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view =  inflater.inflate(R.layout.fragment_fragment1, container, false);
    ((TextView)view.findViewById(R.id.textview)).setText("some text");

    return view;
}

}

但是这些代码调用空指针异常:

public class Fragment1 extends Fragment {
//@Nullable
//@Override
TextView textt;
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view =  inflater.inflate(R.layout.fragment_fragment1, container, false);

    textt =  (TextView)view.findViewById(R.id.textview);
    return view;
}

public void updateText() {
    textt.setText("some text");
}
}

public class Fragment1 extends Fragment {
//@Nullable
//@Override
View view;
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    view =  inflater.inflate(R.layout.fragment_fragment1, container, false);

    return view;
}

public void updateText() {

    ((TextView)view.findViewById(R.id.textview)).setText("some text");
}
}

MainActivity:

public class MainActivity extends AppCompatActivity {

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


    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    Fragment1 frg1 = new Fragment1();
    ft.replace(R.id.fragment_container, frg1);
    ft.addToBackStack(null);
    ft.commit();
    frg1.updateText();
}
}

为什么这些代码会提供不同的结果?

my project

2 个答案:

答案 0 :(得分:1)

在调用片段的onCreateView生命周期方法之前调用

frg1.updateText();。您应该在设置

后调用该方法

textt = (TextView)view.findViewById(R.id.textview);

 View view =  inflater.inflate(R.layout.fragment_fragment1, container, false);

    textt =  (TextView)view.findViewById(R.id.textview);
    this.updateText();//here
    return view;

查看有关onCreateView

fragment lifecycle个文档
  

当片段第一次绘制其用户界面时,系统会调用此方法。

当加载片段而非在活动中创建片段时,会发生这种情况。

答案 1 :(得分:0)

此处,调用updateText函数时不会创建textview。

在片段中进行此类调用。不是关于片段的活动。