如何在 Android listview 中查詢陣列中的公共元素?


本例演示如何在 Android listview 中查詢陣列中的公共元素。

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

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

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
   android:orientation="vertical"
   android:gravity="center_horizontal"
   android:layout_marginTop="30dp"
   tools:context=".MainActivity">
   <ListView
      android:id="@+id/list"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content">
   </ListView>
</LinearLayout>

在程式碼中,我們已經使用 listview 來顯示陣列值。

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

package com.example.myapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

public class MainActivity extends AppCompatActivity {
   ListView list;
   String[] names = new String[] { "A", "B", "C" };
   String[] extended = new String[5];

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      list = findViewById(R.id.list);
      extended[3] = "D";
      extended[4] = "E";
      System.arraycopy(names, 0, extended, 0, names.length);
      ArrayList<String> unique = new ArrayList<>();
      for(int i = 0;i<names.length;i++) {
         for(int j = 0;j<extended.length;j++) {
            if(names[i] == extended[j]) {
               unique.add(names[i]);
            }
         }
      }
ArrayAdapter adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, unique);
list.setAdapter(adapter);
}
}

讓我們嘗試執行你的應用程式。我假設你已經將真實的 Android 移動裝置與計算機連線。要從 Android Studio 執行應用,開啟一個專案活動檔案並單擊工具欄中的執行  圖示。選擇你的移動裝置作為選項,然後檢查將顯示預設螢幕的移動裝置 -

在以上結果中,我們展示了一個常見陣列。

點選 此處 下載專案程式碼

更新於:26-6-2020

115 次瀏覽

啟動你的職業

透過完成本課程取得認證

開始
廣告