實現效果以下android
注:編程
博客:
https://blog.csdn.net/badao_liumang_qizhi
關注公衆號
霸道的程序猿
獲取編程相關電子書、教程推送與免費下載。數組
將佈局改成LinearLayout,並經過android:orientation="vertical">設置爲垂直佈局,而後添加id屬性。app
而後在res下values下新建arrays.xml,數組資源文件,用來存儲listView的選項內容ide
arrays.xml:佈局
<?xml version="1.0" encoding="utf-8"?> <resources> <string-array name="ctype"> <item>所有</item> <item>公衆號</item> <item>霸道</item> <item>的</item> <item>程序猿</item> <item>博客</item> <item>霸道</item> <item>流氓</item> <item>氣質</item> </string-array> </resources>
只要經過name屬性賦值爲ctype,後續被引用。this
而後再回到activity_list_view.xml中,經過spa
android:entries="@array/ctype"
爲listView設置選項數組內容。.net
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" tools:context=".ListViewActivity"> <ListView android:id="@+id/listView" android:entries="@array/ctype" android:layout_width="match_parent" android:layout_height="wrap_content"/> </LinearLayout>
若是不想用這種資源文件的方式,想在代碼中進行賦值,將entries屬性去掉,來到activity中3d
首先聲明一個String數組,而後聲明一個適配器,並獲取listView,最後將適配器與listView綁定
package com.badao.relativelayouttest; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.ListView; public class ListViewActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_list_view); //聲明數組 String[] ctype = new String[]{"所有", "公衆號", "霸道的程序猿", "博客", "霸道流氓氣質"}; //聲明適配器 ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, ctype); //獲取listView ListView listView = (ListView) findViewById(R.id.listView); //關聯適配器與listView listView.setAdapter(adapter); } }