ListView顧名思義,主要用來顯示清單,比如聯絡資訊、商品資訊等相似且重複性高的資料。ListView須利用Adapter來管理每一列的資料與配置。
先於activiity_main.xml加入ListView元件
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
將listView與ListView元件綁定
public class MainActivity extends AppCompatActivity {
ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listView);
}
}
建立一個字串陣列list,並放入資料:"蘋果"、"香蕉"、"橘子"、"葡萄"、"西瓜"。
將list帶入adapter,並設定listView,即可讓listView顯示資料。
String[] list = {"蘋果","香蕉","橘子","葡萄","西瓜"};
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1,list);
listView.setAdapter(adapter);
結果圖:
變數i會回傳目前點擊的項目編號,所以只要將變數i給陣列list,即可取得當前點擊的資料。
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(MainActivity.this,list[i],Toast.LENGTH_SHORT).show();
}
});
效果圖:
public class MainActivity extends AppCompatActivity {
ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listView);
String[] list = {"蘋果","香蕉","橘子","葡萄","西瓜"};
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1,list);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(MainActivity.this,list[i],Toast.LENGTH_SHORT).show();
}
});
}
}