gpt4 book ai didi

android - 如何在android中的gridview中显示arraylist

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:27:42 25 4
gpt4 key购买 nike

我想在 Gridview 中显示 Arraylist 项目。我的 Arraylist 是这样的:

1 你好你好

2 你好你好

如果我像这样将它绑定(bind)到 gridview 控件:

  ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, event_list);

gridview.setAdapter(adapter);

event_List 是我的 Arraylist。通过这种方法,我在 gridview 的单元格中获得了完整的 Arraylist 行或记录。我想在 gridview 的每个单元格中显示每个项目,如 Arraylist 的“Hello”。比如一个单元格中的 1,另一个单元格中的“你好”等等。

提前致谢

最佳答案

似乎你需要使用 BaseAdapter , 因为默认的 ArrayAdapter 无法完成将 ArrayList 元素划分为多个元素。

所以,它看起来像下面这样:

public class MyActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

final GridView grid = (GridView) findViewById(R.id.gridView);
final ArrayList<String> items = new ArrayList<String>();

items.add("1 , Hello11 , Hello12");
items.add("2 , Hello21 , Hello22");

grid.setAdapter(new GridAdapter(items));
}

// Assume it's known
private static final int ROW_ITEMS = 3;

private static final class GridAdapter extends BaseAdapter {

final ArrayList<String> mItems;
final int mCount;

/**
* Default constructor
* @param items to fill data to
*/
private GridAdapter(final ArrayList<String> items) {

mCount = items.size() * ROW_ITEMS;
mItems = new ArrayList<String>(mCount);

// for small size of items it's ok to do it here, sync way
for (String item : items) {
// get separate string parts, divided by ,
final String[] parts = item.split(",");

// remove spaces from parts
for (String part : parts) {
part.replace(" ", "");
mItems.add(part);
}
}
}

@Override
public int getCount() {
return mCount;
}

@Override
public Object getItem(final int position) {
return mItems.get(position);
}

@Override
public long getItemId(final int position) {
return position;
}

@Override
public View getView(final int position, final View convertView, final ViewGroup parent) {

View view = convertView;

if (view == null) {
view = LayoutInflater.from(parent.getContext()).inflate(android.R.layout.simple_list_item_1, parent, false);
}

final TextView text = (TextView) view.findViewById(android.R.id.text1);

text.setText(mItems.get(position));

return view;
}
}
}

将生成包含六个项目的网格。更多见对应Android Guide for Grid View .

关于android - 如何在android中的gridview中显示arraylist,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17417305/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com