ArrayAdapter和ListView


 

 

利用ArrayAdapter向ListView中添加數據

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">
    <!-- 設置使用紅色的分隔條 -->
    <ListView
            android:id="@+id/list1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:divider="#f00"
            android:dividerHeight="1dp"
            android:headerDividersEnabled="false"/>
    <!-- 設置使用綠色的分隔條 -->
    <ListView
            android:id="@+id/list2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:divider="#0f0"
            android:dividerHeight="1dp"
            android:headerDividersEnabled="false"/>
</LinearLayout>
View Code

我們創建數組,並且將之添加到ArrayAdapter,然后跟ListView關聯起來。

val list1 = findViewById<ListView>(R.id.list1)
        // 定義一個數組
        val arr1 = arrayOf("孫悟空", "豬八戒", "牛魔王")
        // 將數組包裝為ArrayAdapter
        val adapter1 = ArrayAdapter(this, R.layout.array_item, arr1)
        // 為ListView設置Adapter
        list1.adapter = adapter1
        val list2 = findViewById<ListView>(R.id.list2)
        // 定義一個數組
        val arr2 = arrayOf("Java", "Hibernate", "Spring", "Android")
        // 將數組包裝為ArrayAdapter
        val adapter2 = ArrayAdapter(this, R.layout.checked_item, arr2)
        // 為ListView設置Adapter
        list2.adapter = adapter2

這里注意,創建adapter是傳入三個參數:

  • contex
  • textViewResourceId,這個是布局文件。
  • 數組或list

布局文件是這樣的:

 

 

詳情是這樣的:

<?xml version="1.0" encoding="utf-8"?>
<CheckedTextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/TextView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"    
    android:textSize="24sp"
    android:checkMark="@drawable/ok"
    android:shadowColor="#f0f"
    android:shadowDx="4"
    android:shadowDy="4"
    android:shadowRadius="2"/>
<?xml version="1.0" encoding="utf-8"?>
<TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/TextView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"    
    android:textSize="24dp"
    android:padding="5dp"
    android:shadowColor="#f0f"
    android:shadowDx="4"
    android:shadowDy="4"
    android:shadowRadius="2"/>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM