im still new in android developement. I want to refresh my fragment and getting new imageButton background in that fragment but i keep failing to do that.
This is my main activity
public class MainActivity extends AppCompatActivity {
public int QuestionNum =0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MainActivityFragment MainFrag = new MainActivityFragment();
getSupportFragmentManager().beginTransaction()
.add(R.id.content, MainFrag).commit();
}
public void Answer1(View view){
QuestionNum++;
Stage StageFrag = new Stage();
getSupportFragmentManager().beginTransaction()
.replace(R.id.content,StageFrag).commit();
}
and this is my fragment
public class Stage extends Fragment {
public Stage() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_stage, container, false);
MainActivity Main = new MainActivity();
String QuestionInd[] = getResources().getStringArray(R.array.Qind);
Integer AnswerAnimal[]={R.drawable.anjing,R.drawable.kucing....};
int QNum = Main.QuestionNum;
TextView Question = (TextView) view.findViewById(R.id.Questions);
Question.setText(QuestionInd[Main.QuestionNum]);
ImageButton Ans1 = (ImageButton) view.findViewById(R.id.Choice1);
ImageButton Ans2 = (ImageButton) view.findViewById(R.id.Choice2);
ImageButton Ans3 = (ImageButton) view.findViewById(R.id.Choice3);
ImageButton Ans4 = (ImageButton) view.findViewById(R.id.Choice4);
switch(QNum) {
case 0:
Ans1.setBackgroundResource(AnswerAnimal[0]);
Ans2.setBackgroundResource(AnswerAnimal[1]);
Ans3.setBackgroundResource(AnswerAnimal[2]);
Ans4.setBackgroundResource(AnswerAnimal[3]);
break;
case 1:
Ans1.setBackgroundResource(AnswerAnimal[8]);
Ans2.setBackgroundResource(AnswerAnimal[9]);
Ans3.setBackgroundResource(AnswerAnimal[5]);
Ans4.setBackgroundResource(AnswerAnimal[4]);
break;
}
return view;
}
}
i didnt get error in my logcat. I also try using add but the background didn't change only the fragments keep stacking. Using the attach and retach didnt work too.
Please help me and explain my mistake. i really want to learn about this. Thank you.