Java 无法从片段在主活动中创建按钮?
例如,我想在MainActivity.java中创建一个按钮,它位于不同的片段中 更清楚一点,我有一个包含3个片段的活动,我想从该活动中的片段2创建一个按钮。但是当尝试初始化它们时,我得到一个空指针异常Java 无法从片段在主活动中创建按钮?,java,android,android-fragments,nullpointerexception,fragment,Java,Android,Android Fragments,Nullpointerexception,Fragment,例如,我想在MainActivity.java中创建一个按钮,它位于不同的片段中 更清楚一点,我有一个包含3个片段的活动,我想从该活动中的片段2创建一个按钮。但是当尝试初始化它们时,我得到一个空指针异常 protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_quiz); i
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
if (savedInstanceState == null) {
fragmentManager = getFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.scoreFragment, new ScoreFragment());
fragmentTransaction.add(R.id.questionFragment, new QuestionFragment());
fragmentTransaction.add(R.id.navigationFragment, new NavigationFragment());
//creates the questions
questions = new ArrayList<Question>();
currentQuestion = new Question("correct");
questions.add(currentQuestion);
fragmentTransaction.commit();
//here is where the null pointer exception appears.
QuestionFragment q = (QuestionFragment) fragmentManager.findFragmentById(R.id.questionFragment);
//View v = q.;
initialize(q);
}
//Button nextQuestionButton = (Button) findViewById(R.id.next);
//nextQuestionButton.setEnabled(false);
}
/* WHY DOESNT IT WORK? */
private void initialize(QuestionFragment q){
View v=q.getView();
buttons[0] = (Button) v.findViewById(R.id.button1);
buttons[1] = (Button) v.findViewById(R.id.button2);
buttons[2] = (Button) v.findViewById(R.id.button3);
buttons[3] = (Button) v.findViewById(R.id.button4);
//loads possible answers from array
Resources res = getResources();
String[] answers = res.getStringArray(R.array.questionBank);
//creates a random number between 0 and 3 that button is correct and the others are incorrect
Random rand = new Random();
int correct = rand.nextInt(4);
buttons[correct].setText(answers[0]);
buttons[(correct + 1) % 4].setText(answers[1]);
buttons[(correct + 2) % 4].setText(answers[2]);
buttons[(correct + 3) % 4].setText(answers[3]);
}
如果我在onCreateView中的QuestionFragment中创建按钮,我会让它工作,但我想尝试在QuizaActivity中工作,它包含3个片段
如何执行此操作?尝试在QuestionFragment类中重写onCreateView,并在那里执行QuestionFragment UI初始化,而不是尝试从活动级别对其进行管理
此外,在上面的示例中,如果fragmentManager.findFragmentByIdR.id.questionFragment返回null,则表示该片段尚未添加/不存在。为什么要在活动中执行此操作。片段应该处理它们自己的功能。我实际上初始化了有问题的ui片段类,它工作了,但我不确定这是否是正确的方法。另外,我想知道它在MainActivity上不起作用的原因。这是正确的方法。通常,将片段视为子活动:可以包含或封装在片段中的所有逻辑都应该放在那里,而不是活动。如果您不遵循此模式,那么您的所有逻辑都将绑定到该活动,并且您将无法在不同的活动中轻松地重用片段,这有点违背了片段的全部目的。