0

다른 단편에있는 예를 들어 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]); 
    } 

은 내가 onCreateViewQuestionFragment에있는 버튼을 만들 경우 작동하도록있어하지만 난 3 개 조각을 보유하고, QuizActivity에서 작동하게 만들려고 노력하고 싶습니다.

어떻게하면됩니까?

+0

왜 활동에서이 작업을 수행 하시겠습니까? 단편은 자체 기능을 처리해야합니다. – HackerMaker36

답변

0

QuestionFragment 클래스에서 onCreateView를 재정 의하여 시도하고 QuestionFragment UI 초기화를 작업 수준에서 관리하지 말고 수행하십시오.

또한 위 예제에서 fragmentManager.findFragmentById (R.id.questionFragment)가 null을 반환하면 조각이 추가되지 않았거나 존재하지 않는다는 것을 의미합니다.

+0

사실 Question 클래스에서 UI를 초기화했고 제대로 작동하는지는 모르지만 잘 작동하지 않습니다. 또한 MainActivity에서 작동하지 않는 이유를 알고 싶습니다. – Smeekheff

+0

올바른 방법입니다. 일반적으로 Fragment를 하위 활동으로 생각하십시오. Fragment 내에 포함되거나 캡슐화 될 수있는 모든 로직은 Activity와 비교하여 이동해야합니다. 이 패턴을 따르지 않으면 모든 논리가 해당 활동에 바인딩되고 다른 활동에서 단편을 쉽게 재사용 할 수 없게됩니다 (단편의 모든 목적을 무효로합니다). – craigrs84

+0

나를 혼란스럽게 해 주셔서 감사합니다. 고맙습니다. – Smeekheff

관련 문제