vignesh baskar vignesh baskar - 4 years ago 92
Android Question

Dynamic creation of layout and swapping them in android

I want a create a quiz app in android in which I want to dynamically change the questions for every 60 seconds in the same layout where the number of question vary dynamically.

I planned to do a quiz system which creates layout dynamically and changes it between some interval.

I tried with a countdown Timer but it's not accurate.

protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student_main);

String[] fr={"National Bird Of India?","How is your life?","What's yourFavourite dish","Whats your hobby","Whats your skin color"};
String s="";
int i;

i=0;
int seconds=10000;

CountDownTimer countDownTimer = new CountDownTimer((fr.length*seconds)+seconds, seconds)
{
@Override
public void onTick(long l)
{

String s = String.valueOf(l);
char[] f = s.toCharArray();
textView.setText(String.valueOf(i+1));
textView2.setText(fr[i]);
if(!s.equals(String.valueOf(f[0])))
{
textView2.setText(fr[i]);
i++;
}
else
{
s=String.valueOf(f[0]);
}
}
@Override
public void onFinish()
{
Intent intent=new Intent(getBaseContext(),Finish_quiz.class);
startActivity(intent);
finish();
}
};
countDownTimer.start();
}

Answer Source

Your question is very vague but looks like fragments are what you need. Assuming you know about Fragments in Android, they are designed for the exact purpose of changing your UI look and feel on the go within the same container (which in Android terminology is the Activity component).

So consider you have 50 questions and all of them roughly falls under 5 segments requiring you to design 5 different layouts. So what you do is define 5 different fragments with their distinct look and feel. Albeit you can always reuse individual UI components among fragments which is what you should do, thus requiring you to write lesser code.

Now when you want to display a different UI for the next question, you can just replace the current fragment in the UI. For performance sake, you can create instance of all the 5 fragments type in your activity start and just go on replacing the current viewable fragment.

Please read upon - https://developer.android.com/training/basics/fragments/fragment-ui.html

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download