At first the problem was getView() always returns null in my fragment . so as others offer I used a View in onCreateView to get view like this :
private View vv ;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
vv = inflater.inflate(R.layout.fragment_exam_page2, container, false); ;
return vv ;
}
so I could use vv instead of getView() . But now I see that onCreateView does not get called at all ! in my activity I do this :
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
TwoLineOptionsFragment twoLineOptionsFragment = new TwoLineOptionsFragment();
transaction.replace(R.id.fragment_answerContainer, twoLineOptionsFragment).commit();
twoLineOptionsFragment.updateOptions(question.AnswerOptions) ;// my public function doing stuff ...
so where is the problem ?
EDIT : here is my function if matters :
public boolean updateOptions(ArrayList<Exam.Question.Answer> answers)
{
try
{
QuestionOptionView optionView = (QuestionOptionView)(vv.findViewById(R.id.option1)) ;
//QuestionOptionView optionView = (QuestionOptionView)(getView().findViewById(R.id.option1)) ;
optionView.setText(answers.get(0).AnswerText);
return reue ;
}
// ...
}
答案 0 :(得分:2)
onCreateView()将始终被调用。您遇到的问题是在调用onCreateView()之前尝试访问视图对象。以下内容过早执行。
true
请勿直接从活动中调用 twoLineOptionsFragment.updateOptions(question.AnswerOptions) ;
方法,因为您可能不确定Fragment
是否已准备就绪。您应该将您的逻辑移动到Fragment
类本身并提供对Fragment
的回调,以便您可以将结果传递回活动。
在您的情况下,您可以将Activity
值作为参数传递给Fragment并将其显示在TextView上。干杯:)
answers.get(0).AnswerText