Reputation: 111
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 ;
}
// ...
}
Upvotes: 0
Views: 1475
Reputation: 11481
onCreateView() of Fragment will get called always. The problem in your case is you are trying to access the view object before onCreateView() get called. The following get executed too early.
twoLineOptionsFragment.updateOptions(question.AnswerOptions) ;
Don't call Fragment
methods directly from the activity, because you may not sure that Fragment
is ready or not. You should move your logic into Fragment
class itself and provide a callback to Activity
so that you can pass results back to the Activity.
In your case, you can pass answers.get(0).AnswerText
value as an argument to Fragment and display it on the TextView. cheers :)
TwoLineOptionsFragment f = new TwoLineOptionsFragment();
Bundle args = new Bundle();
args.putString("arg", answers.get(0).AnswerText);
f.setArguments(args);
Upvotes: 2