我创建了一个自定义类来快速创建View对象(基本上它只是一个显示的问题)。例如:
标题:天气
消息:今天天气怎么样?
所以这是我的自定义类扩展View:
public class Question extends View {
Context mContext;
public Question(Context context) {
super(context);
mContext = context;
}
public void addQuestion (View rootView, String title, String message) {
// Inflate une question
LinearLayout rootQuestion = (LinearLayout) rootView.findViewById(R.id.activity_formulaire_questions_preliminaires_ll_wrapper);
LayoutInflater questionInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout myQuestion = (LinearLayout) questionInflater.inflate(R.layout.activity_formulaire_question, rootQuestion);
// Assigne la vue au controlleur
TextView tvTitle = (TextView) myQuestion.findViewById(R.id.activity_formulaire_question_title);
TextView tvMessage = (TextView) myQuestion.findViewById(R.id.activity_formulaire_question_message);
// Remplissage des champs textes
tvTitle.setText(title);
tvMessage.setText(message);
}
我的片段:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.activity_formulaire_questions_preliminaires, null);
Question question = new Question(super.getActivity());
question.addQuestion(rootView, "Question 1 Title", "1");
question.addQuestion(rootView, "Question 2 Title", "2");
question.addQuestion(rootView, "Question 3 Title", "3");
question.addQuestion(rootView, "Question 4 Title", "4");
return rootView;
}
但是在启动片段时,它只是正确显示的最后一个问题。
- >问题4标题
- >默认标题
- >默认标题
- >默认标题
为什么?我在使用questionInflater.inflate时会得到一个新视图,并尊重层次结构“View - > ViewGroup - > LinearLayout”
答案 0 :(得分:2)
您可以通过多种方式解决此问题。 例如,在这种情况下,您不需要实际扩展View。
这样的事情应该有效:
public class QuestionHelper {
Context mContext;
public QuestionHelper(Context context) {
mContext = context;
}
public void addQuestion(ViewGroup rootView, String title, String message) {
// Inflate une question
LayoutInflater questionInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout myQuestion = (LinearLayout) questionInflater.inflate(R.layout.activity_formulaire_question, null, false);
// Assigne la vue au controlleur
TextView tvTitle = (TextView) myQuestion.findViewById(R.id.activity_formulaire_question_title);
TextView tvMessage = (TextView) myQuestion.findViewById(R.id.activity_formulaire_question_message);
// Remplissage des champs textes
tvTitle.setText(title);
tvMessage.setText(message);
rootView.addView(myQuestion);
}
}
在你的片段上:
QuestionHelper questionHelper = new QuestionHelper(this);
questionHelper.addQuestion(rootView, "Question 1 Title", "1");
questionHelper.addQuestion(rootView, "Question 2 Title", "2");
questionHelper.addQuestion(rootView, "Question 3 Title", "3");
questionHelper.addQuestion(rootView, "Question 4 Title", "4");