我知道如何填充listview,也知道如何制作自定义适配器。我想在ListView的rowLayout的线性布局内添加View。这是MyList适配器。
我想要一个在运行时创建每个项目布局的列表视图,但是我无法实现这一点。
这段代码在没有ListView的情况下可以工作,但是当我将其添加到listview内的Linearlayout时,它给了我错误。
public class KmapListAdapter extends BaseAdapter {
Context context;
LayoutInflater layoutInflater;
List<KmapModel> mOriginalValues = new ArrayList<KmapModel>();
public KmapListAdapter(Context activity, List<KmapModel> kmapModelList) {
this.context = activity;
this.mOriginalValues = kmapModelList;
}
@Override
public int getCount() {
if(mOriginalValues == null)
return 0;
return mOriginalValues.size();
}
@Override
public Object getItem(int position) {
return mOriginalValues.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
ViewHolder Holder ;
@Override
public View getView(int position, View convertView, ViewGroup parent) {
KmapModel kmapModel;
if (layoutInflater == null)
layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
Holder = new ViewHolder();
convertView = layoutInflater.inflate(R.layout.rowlayout, null);
Holder.linearLayout = (LinearLayout) convertView.findViewById(R.id.linear_layout_matrix_1);
convertView.setTag(Holder);
} else
Holder = (ViewHolder) convertView.getTag();
kmapModel = mOriginalValues.get(position);
Holder.linearLayout.addView(kmapModel.getLinearLayout());
return convertView;
}
static class ViewHolder {
LinearLayout linearLayout;}}
这是我的型号清单
public List<KmapModel> ListViewOneItem( int ROWS, int COLS) {
String[][] KmapArray = KMapMaker(ROWS, COLS);
// Log.v("Kmap array",""+KmapArray);
TextView[][] KmapTextView = new TextView[KmapArray.length][KmapArray[0].length];
int temp = 3;
for (int i = 0; i < KmapArray.length; i++) {
KmapModel kmapModel = new KmapModel();
LinearLayout rowLinearLayout = makeRowLinearLayout();
for (int j = 0; j < KmapArray[0].length; j++) {
TextView rowTextView = makeTextView();
rowTextView.setPadding(4, 4, 4, 4);
rowLinearLayout.addView(rowTextView);
KmapTextView[i][j] = rowTextView;// Add a text view in a jagged array for later use
}
kmapModel.setLinearLayout(rowLinearLayout);
kmapModelList.add(kmapModel);
}
return kmapModelList;
}
现在我得到一个错误
指定的孩子已经有一个父母。您必须先在孩子的父母上调用removeView()。在这条线上
Holder.linearLayout.addView(kmapModel.getLinearLayout());
Q1)如何解决此问题Q2)为什么会出现此问题?
感谢@pskink,他给了我一种尝试的方式,然后我上传了解决方案。
指定的孩子已经有一个父母。
不要再给孩子第二个父母了。所有的观点都来自破碎的家园。他们有一个父母。
您可以向视图添加视图,不能添加已经添加的视图。这会导致循环,并且循环是循环的。为了成功地迭代视图树,它必须是一棵树。因此,视图只有一个父视图。清除现有的布局并使用它,或者将新视图添加到布局中,或者基本上不需要在视图树的多个位置使用同一对象的任何内容。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句