我查看了类似的问题但尚未找到答案。在从SQL数据库获取数据后,我最终将添加每个View
,但是现在,我只是尝试添加一组视图,以便我可以使我的布局正常工作。我有一个带有片段管理器的主要活动,可以让我的标签流动并加载得很好,所以我认为我不需要在这里提供该代码。
以下是片段的代码:
public class EconFragment extends Fragment {
private ViewGroup container;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
populateQuestions(container, inflater);
return inflater.inflate(R.layout.econfragment, container, false);
}
public void onPause() {
super.onPause();
container.removeAllViews();
}
private void populateQuestions(ViewGroup v, LayoutInflater inflater) {
container = v;
int count = 10;
int runner = 0;
while (runner < count) {
View question = inflater.inflate(R.layout.question, null);
question.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
container.addView(question, runner);
runner++;
}
}
}
因此,虽然这应该在容器中填充多个Question.xml视图,但我只有一个显示。值得注意的是,我可以观察到跑步者增加到计数时的延迟,但同样只会出现一个问题视图。当我改变时,我在TableLayout
周围得到很多空指针,所以我删除了那部分。
最终,EconFragment
的xml有一个表格布局,其中ScrollView
还有另一个TableLayout
,questionContainer。
我原本希望将每个问题视图添加到questionContainer
中,但这会给我带来各种麻烦。我认为这与在populateQuestions()
中返回语句之前调用onCreateView()
有点相关?
答案 0 :(得分:1)
以下是我解决问题的方法。它没有实现我想要的SQL dB访问,它只是一个填充while循环和一个虚拟的字符串数组来制作Table Rows。我几乎已经通过SQL dB实现了登录/注册,一旦完成,通过SQL填充这些tablerow应该不是一个大问题。
public class EconFragment extends Fragment {
private TableLayout questionContainer;
static int pos = 0;
private String[] titles = {"The first title ", "hallo1","hallo2", "hallo3",
"hallo4", "hallo5","hallo6", "hallo7","hallo8", "hallo9"};
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.d("Econ", "onCreateView");
return inflater.inflate(R.layout.econfragment, container, false);
}
public void onResume() {
super.onResume();
LayoutInflater inflater = (LayoutInflater) getActivity().
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
questionContainer = (TableLayout) getActivity().findViewById(R.id.questionContainer);
//these lines are my first attempt to try and get the questions to repopulate after returning
//from pressing back - as of yet, they don't repopulate the screen:
//View econFragment = inflater.inflate(R.layout.econfragment, null);
//container.addView(econFragment);
int leftMargin=5;
int topMargin=5;
int rightMargin=5;
int bottomMargin=5;
while (pos < 10) {
View question = inflater.inflate(R.layout.question, null);
question.setId(pos);
TextView title = (TextView) question.findViewById(R.id.questionTextView);
title.setText(titles[pos]);
Button charts = (Button) question.findViewById(R.id.chartsButton);
charts.setId(pos);
charts.setOnClickListener(chartsListener);
TableRow tr = (TableRow) question;
TableLayout.LayoutParams trParams = new TableLayout.LayoutParams(
TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT);
trParams.setMargins(leftMargin, topMargin, rightMargin, bottomMargin);
tr.setLayoutParams(trParams);
questionContainer.addView(tr);
pos++;
}
Log.d("Econ", "onResume");
}