如何在Android中建立自定義ListView?


在進入ListView示例之前,我們應該瞭解ListView。ListView是從ArrayList、List或任何資料庫中提取專案的集合。ListView最常用的用途是以垂直格式顯示專案的集合,我們可以上下滾動並點選任何專案。

什麼是自定義ListView?

自定義ListView基於自定義介面卡(customAdapter)。在這個自定義介面卡中,我們可以傳遞自定義物件。我們像下面這樣將主題資料傳遞給ListView:

**步驟1** - 在Android Studio中建立一個新專案,轉到檔案 ⇒ 新建專案,並填寫所有必需的詳細資訊以建立新專案。

**步驟2** - 將以下程式碼新增到res/layout/activity_main.xml。

<?xml version = "1.0" encoding = "utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent"
   android:layout_height = "match_parent">
<LinearLayout
   android:layout_width = "match_parent"
   android:layout_height = "match_parent"
   android:orientation = "vertical">
   <ListView
      android:id = "@+id/list"
      android:layout_width = "wrap_content"
      android:layout_height = "match_parent"
      android:divider = "#000"
      android:dividerHeight = "1dp"
      android:footerDividersEnabled = "false"
      android:headerDividersEnabled = "false"/>
</LinearLayout>
</android.support.constraint.ConstraintLayout>

在上面的activity_main.xml中,我們聲明瞭一個ListView並添加了分隔符,如下所示。

<ListView
   android:id = "@+id/list"
   android:layout_width = "wrap_content"
   android:layout_height = "match_parent"
   android:divider = "#000"
   android:dividerHeight = "1dp"
   android:footerDividersEnabled = "false"
   android:headerDividersEnabled = "false"
/>

**步驟3** - 將以下程式碼新增到src/MainActivity.java

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      final ListView list = findViewById(R.id.list);
      ArrayList<SubjectData> arrayList = new ArrayList<SubjectData>();
      arrayList.add(new SubjectData("JAVA", "https://tutorialspoint.tw/java/",             "https://tutorialspoint.tw/java/images/java-mini-logo.jpg"));
      arrayList.add(new SubjectData("Python", "https://tutorialspoint.tw/python/", "https://tutorialspoint.tw/python/images/python-mini.jpg"));
      arrayList.add(new SubjectData("Javascript", "https://tutorialspoint.tw/javascript/", "https://tutorialspoint.tw/javascript/images/javascript-mini-logo.jpg"));
      arrayList.add(new SubjectData("Cprogramming", "https://tutorialspoint.tw/cprogramming/", "https://tutorialspoint.tw/cprogramming/images/c-mini-logo.jpg"));
      arrayList.add(new SubjectData("Cplusplus", "https://tutorialspoint.tw/cplusplus/", "https://tutorialspoint.tw/cplusplus/images/cpp-mini-logo.jpg"));
      arrayList.add(new SubjectData("Android", "https://tutorialspoint.tw/android/", "https://tutorialspoint.tw/android/images/android-mini-logo.jpg"));
      CustomAdapter customAdapter = new CustomAdapter(this, arrayList);
      list.setAdapter(customAdapter);
   }
}

在MainActivity中,我們聲明瞭CustomAdapter並傳遞了SubjectData,如下所示:

CustomAdapter customAdapter = new CustomAdapter(this, arrayList);
list.setAdapter(customAdapter);

**步驟4** - 建立一個CustomAdapter類,將以下程式碼新增到src/CustomAdapter.java

import android.content.Context;
import android.database.DataSetObserver;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
class CustomAdapter implements ListAdapter {
   ArrayList<SubjectData> arrayList;
   Context context;
   public CustomAdapter(Context context, ArrayList<SubjectData> arrayList) {
      this.arrayList=arrayList;
      this.context=context;
   }
   @Override
   public boolean areAllItemsEnabled() {
      return false;
   }
   @Override
   public boolean isEnabled(int position) {
      return true;
   }
   @Override
   public void registerDataSetObserver(DataSetObserver observer) {
   }
   @Override
   public void unregisterDataSetObserver(DataSetObserver observer) {
   }
   @Override
   public int getCount() {
      return arrayList.size();
   }
   @Override
   public Object getItem(int position) {
      return position;
   }
   @Override
   public long getItemId(int position) {
      return position;
   }
   @Override
   public boolean hasStableIds() {
      return false;
   }
   @Override
   public View getView(int position, View convertView, ViewGroup parent) {
      SubjectData subjectData=arrayList.get(position);
      if(convertView==null) {
         LayoutInflater layoutInflater = LayoutInflater.from(context);
         convertView=layoutInflater.inflate(R.layout.list_row, null);
         convertView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            }
         });
         TextView tittle=convertView.findViewById(R.id.title);
         ImageView imag=convertView.findViewById(R.id.list_image);
         tittle.setText(subjectData.SubjectName);
         Picasso.with(context)
         .load(subjectData.Image)
         .into(imag);
      }
      return convertView;
   }
   @Override
   public int getItemViewType(int position) {
      return position;
   }
   @Override
   public int getViewTypeCount() {
      return arrayList.size();
   }
   @Override
   public boolean isEmpty() {
      return false;
   }
}

**步驟5** - 建立一個SubjectData類,將以下程式碼新增到src/SubjectData.java

class SubjectData {
   String SubjectName;
   String Link;
   String Image;
   public SubjectData(String subjectName, String link, String image) {
      this.SubjectName = subjectName;
      this.Link = link;
      this.Image = image;
   }
}

**步驟6** - 在CustomAdapter類中,我們顯示了網路圖片資源。為了顯示網路圖片資源,我們添加了Picasso庫,如下所示。

Picasso.with(context)
.load(subjectData.Image)
.into(imag);

**步驟7** - 為了實現Picasso庫,我們必須在gradle中新增Picasso庫,如下所示。

apply plugin: 'com.android.application'
android {
   compileSdkVersion 28
   defaultConfig {
      applicationId "com.example.andy.myapplication"
      minSdkVersion 15
      targetSdkVersion 28
      versionCode 1
      versionName "1.0"
      testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
   }  
   buildTypes {
      release {
         minifyEnabled false
         proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
      }
   }
}
dependencies {
   implementation fileTree(dir: 'libs', include: ['*.jar'])
   implementation 'com.android.support:appcompat-v7:28.0.0'
   implementation 'com.android.support.constraint:constraint-layout:1.1.3'
   testImplementation 'junit:junit:4.12'
   implementation 'com.squareup.picasso:picasso:2.5.1'
   androidTestImplementation 'com.android.support.test:runner:1.0.2'
   androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

**步驟8** - 為了訪問網際網路資訊,我們必須在清單檔案中授予網際網路許可權,如下所示。

<?xml version = "1.0" encoding = "utf-8"?>
<manifest xmlns:android = "http://schemas.android.com/apk/res/android"
   package = "com.example.andy.myapplication">
<uses-permission android:name = "android.permission.INTERNET"/>
   <application
      android:allowBackup = "true"
      android:icon = "@mipmap/ic_launcher"
      android:label = "@string/app_name"
      android:roundIcon = "@mipmap/ic_launcher_round"
      android:supportsRtl = "true"
      android:theme = "@style/AppTheme">
      <activity android:name = ".MainActivity">
         <intent-filter>
            <action android:name = "android.intent.action.MAIN" />
            <category android:name = "android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>

讓我們嘗試執行您的應用程式。我假設您已將您的實際Android移動裝置連線到您的計算機。要在Android Studio中執行該應用程式,請開啟專案中的一個活動檔案,然後單擊執行  播放圖示 工具欄中的圖示。選擇您的移動裝置作為選項,然後檢查您的移動裝置,它將顯示您的預設螢幕。

Default Output Screen

點選這裡下載專案程式碼

更新於:2019年7月30日

3K+ 次瀏覽

啟動您的職業生涯

透過完成課程獲得認證

開始學習
廣告