I am designing an app which contains around 25 questions.
How to keep changing the questions when i click the next button. So here the layout remains the same except the question (ie the TextView
may change according to different questions but other elements like Buttons
, background will not change).So creating many layout for different questions is time consuming.
So how can I use the same layout
for these many questions.Should I create these many layouts and classes
for asking each question??
You should store your questions in a database, or in a static final String[]
if there aren't many of them.
Multiple classes are not required here, because you only change the question text, ie questionView.setText(newQuestion);
.
Then you need 2 buttons - yes and no, which have an OnClickListener
set to them, which in return sets the questionView
's text with the newQuestion
.
Create a class which will extend Fragment
. Use your standard layout inside onCreateView
.
Create a method inside this class like this:
public static FragmentName newInstance(int question)
{
FragmentName fragment = new FragmentName();
Bundle args = new Bundle();
args.putInt("QUESTION_ID", question);
fragment.setArguments(args);
return fragment;
}
Now inside your fragment's onCreateView
method add some code to check the question number and edit the layout as needed
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
/* ... Code to inflate your layout ... */
Bundle arguments = getArguments();
int question = arguments.getInt("QUESTION_ID", 0);
switch(question)
{
/* Add your code in here to modify the layout */
}
/*... ....*/
}
Now just use a fragment manager
from your activity to handle the transitions, using FragmentName.newInstance(question_number)
to instantiate the single fragments.
This is of course if just programmatically editing the Views from inside the Activity is not enough.
Create different classes
but use the same layout
for every class. and show/hide required textviews
in each class.
Suppose you have parent layout which contain item(Parent view of question just like view container) and resolve it after that infalte your question layout by using this code. and replace the just values on the OnClickListener
of yes button.
RelativeLayout item = (RelativeLayout)findViewById(R.id.item);
View child = getLayoutInflater().inflate(R.layout.child, null);
// Access chile view by child.getElementById(id)
item.addView(child);
When you click yes or no change the textview content accrodingly;
yes_button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
tv_question.setText("This is a new question");.
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.