问题是,我不想用包含图像、描述和两个按钮的元素制作 ListView。我在我自己的 BaseAdapter 扩展中制作它们,但包含 ListView 的 fragment 正在关闭(logcat 中没有错误..)。我发现,当我不返回布局类型元素时,ListView 运行良好。所以我的示例带有“示例线性布局”,但它不起作用。是否有可能在 ListView 中显示布局?
这是我的代码: 创建部分:
lv = (ListView) getView().findViewById(R.id.main_wall_ambajes_lv);
AmbajAdapter aa = new AmbajAdapter(getActivity().getApplicationContext(), StaticData.ambajes);
lv.setAdapter(aa);
来自适配器的我的 getView 方法:
public View getView(int position, View convertView, ViewGroup parent) {
LinearLayout ll = new LinearLayout(getActivity());
ll.setOrientation(LinearLayout.VERTICAL);
ImageView iv = new ImageView(getActivity());
iv.setImageBitmap(placeholderBitmap);
ll.addView(iv);
ll.addView(iv);
ll.addView(iv);
ll.addView(iv);
return ll;
}
最佳答案
我不知道为什么你没有任何错误,但我认为你没有按照正确的方式进行。
通常您在布局文件夹的 xml 文件中创建布局,并且仅在 getView()
中对其进行扩充,例如如下所示:
private LayoutInflater mInflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
@Override
public View getView(int position, View view, ViewGroup parent) {
if (view == null) {
view = mInflater.inflate(R.layout.your_custom_layout, parent, false);
}
//your code for setting the image or other things goes here
//for example if you have a textView
TextView textView = (TextView) view.findViewById(R.id.my_textview_id);
textView.setText("my custom text for this cell");
return (view);
}
your_custom_layout
只是布局的 xml 文件。
注意,出于性能原因,由于单元格回收,我只在 View 为 null 时膨胀 View ,并且我只读取一次 LayoutInflater
上下文并将其放入 mInflater
。但是,为了获得最佳性能,您应该使用 ViewHolder
,但这超出了您的问题范围。
关于Android - 将布局 View 添加到 ListView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25181028/