다른 단편에있는 예를 들어 MainActivity.java
에 버튼을 만들고 싶습니다.조각에서 주요 활동의 단추를 만들 수 없습니까?
좀 더 명확히하기 위해, 나는 3 개의 단편을 보유하고있는 Activity를 가지고 있는데, 그 단편에서 단편 2의 버튼을 만들고 싶습니다. 하지만 그들을 초기화하려고하면 null 포인터 예외가 발생합니다.
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
에있는 버튼을 만들 경우 작동하도록있어하지만 난 3 개 조각을 보유하고,
QuizActivity
에서 작동하게 만들려고 노력하고 싶습니다.
어떻게하면됩니까?
왜 활동에서이 작업을 수행 하시겠습니까? 단편은 자체 기능을 처리해야합니다. – HackerMaker36