listview控件怎么设置横向多个列

avatar
作者
筋斗云
阅读量:0

要在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来显示每个格子的数据。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!