Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android編程入門 >> Android——列表視圖 ListView(一)Arrayadapter

Android——列表視圖 ListView(一)Arrayadapter

編輯:Android編程入門

一、ArrayAdapter 只顯示文字

activitylistview_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/listview_1"
    android:divider="#0f0"
    android:dividerHeight="2dp">

</ListView>
listview_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:textSize="30dp"
    android:gravity="center_vertical"
    android:paddingLeft="10dp">

</TextView>

java

Activitylistview.java

package com.example.chenshuai.test321;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class Activitylistview extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activitylistview_layout);

        ListView listview_1 = (ListView)findViewById(R.id.listview_1);

        //設置listview的適配器Adapter
        //准備數據
        //String[] str_1 = {"a","b","c","d","e","f","g","h","i","j","k","l"};


        //另一種寫法
        List<String> list = new ArrayList<String>();

        list.add("a");
        list.add("b");
        list.add("c");
        list.add("d");
        list.add("e");
        list.add("f");
        list.add("g");
        list.add("h");
        list.add("i");
        list.add("j");
        list.add("k");
        list.add("l");
        list.add("m");
        list.add("n");


        //構造適配器
        ArrayAdapter adapter = new ArrayAdapter(this,R.layout.listview_layout,list);

        //設置適配器
        listview_1.setAdapter(adapter);

        //監聽事件
        listview_1.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                
                //通過下標來獲取內容
                String str = parent.getItemAtPosition(position).toString();

                Toast.makeText(Activitylistview.this, str, Toast.LENGTH_SHORT).show();

                //position 數據的下標  id 數據的id
                Toast.makeText(Activitylistview.this, "position="+position+"id="+id, Toast.LENGTH_SHORT).show();
            }
        });

    }
}

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved