要在ListView控件中設置橫向多個列,可以使用GridView作為ListView的子控件。
以下是一個示例:
activity_main.xml:
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
list_item.xml:
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gridView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:columnWidth="100dp"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center"/>
MainActivity.java:
public class MainActivity extends AppCompatActivity {
private ListView listView;
private List<List<String>> data;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listView);
// 初始化數據
data = new ArrayList<>();
for (int i = 0; i < 20; i++) {
List<String> row = new ArrayList<>();
for (int j = 0; j < 3; j++) {
row.add("Item " + i + "-" + j);
}
data.add(row);
}
// 設置適配器
MyAdapter adapter = new MyAdapter(data);
listView.setAdapter(adapter);
}
private class MyAdapter extends BaseAdapter {
private List<List<String>> data;
public MyAdapter(List<List<String>> data) {
this.data = data;
}
@Override
public int getCount() {
return data.size();
}
@Override
public Object getItem(int position) {
return data.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(MainActivity.this).inflate(R.layout.list_item, parent, false);
}
GridView gridView = convertView.findViewById(R.id.gridView);
ArrayAdapter<String> gridAdapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, data.get(position));
gridView.setAdapter(gridAdapter);
return convertView;
}
}
}
這樣就可以在ListView中顯示橫向多個列的數據了。每個Item使用GridView來顯示多列數據,通過設置GridView的numColumns屬性為auto_fit可以自動根據屏幕大小調整顯示列數。用數組適配器ArrayAdapter來顯示每個格子的數據。