无法在片段中的主要活动中创建按钮?

时间:2014-06-17 18:21:04

标签: java android android-fragments nullpointerexception fragment

我想在MainActivity.java中创建一个按钮,例如,它位于不同的片段中。

为了更清楚一点,我有一个包含3个片段的Activity,我想从该Activity中的片段2创建一个按钮。但是在尝试初始化它们时,我得到一个空指针异常。

    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]); 
    }

如果我在QuestionFragment的{​​{1}}中创建按钮,我就可以使用它,但我想尝试使其在onCreateView中工作,其中包含3个片段。< / p>

我该怎么做?

1 个答案:

答案 0 :(得分:0)

尝试覆盖QuestionFragment类中的onCreateView,并在那里进行QuestionFragment UI初始化,而不是尝试从Activity级别管理它。

此外,在上面的示例中,如果fragmentManager.findFragmentById(R.id.questionFragment)返回null,则表示该片段尚未添加/不存在。