public class MainActivity extends AppCompatActivity {
private FragmentManager fm;
private FragmentTransaction ft;
private Button bt;
private Fraga fa;
@Override
//加载Fragment
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fm = getFragmentManager();
ft = fm.beginTransaction();
fa = new Fraga();
ft.add(R.id.fraga, fa, "fa");
ft.commit();
}
@Override
protected void onStart() {
super.onStart();
// 获得Fragment的控件
Button bt = (Button) fa.getView().findViewById(R.id.button);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
TextView tv = (TextView) fa.getView().findViewById(R.id.textView);
tv.setText("MainActivity");
}
});
}
}
//如果在onCreate方法中去获取Fragment的控件,可能因Fragment
被加载之前调用 getView 方法,会出空指针错误。