如何在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"
   tools:context="MainActivity">
   <LinearLayout
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:gravity="center"
      android:orientation="horizontal">
   <Button
      android:id="@+id/viewCheckedItem"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Select all" />
   </LinearLayout>
   <ListView
      android:id="@+id/listView"
      android:layout_width="match_parent"
      android:layout_height="0dp"
      android:layout_marginTop="30dp"
      android:layout_weight="1">
   </ListView>
</LinearLayout>

步驟 3 - 建立一個 Java 類(CustomAdapter.java)並新增以下程式碼 -

import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Objects;
class CustomAdapter extends BaseAdapter {
   private Context context;
   private static ArrayList<Model> modelArrayList;
   CustomAdapter(Context context, ArrayList<Model> modelArrayList) {
      this.context = context;
      CustomAdapter.modelArrayList = modelArrayList;
   }
   @Override
   public int getViewTypeCount() {
      return getCount();
   }
   @Override
   public int getItemViewType(int position) {
      return position;
   }
   @Override
   public int getCount() {
      return modelArrayList.size();
   }
   @Override
   public Object getItem(int position) {
      return modelArrayList.get(position);
   }
   @Override
      public long getItemId(int position) {
      return 0;
   }
   @SuppressLint("InflateParams")
   @Override
   public View getView(int position, View convertView, ViewGroup parent) {
      final ViewHolder holder;
      if (convertView == null) {
         holder = new ViewHolder();
         LayoutInflater inflater = (LayoutInflater)
         context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
         convertView = Objects.requireNonNull(inflater).inflate(R.layout.listitem, null, true);
         holder.checkBox = convertView.findViewById(R.id.checkBox);
         holder.tvPlayer = convertView.findViewById(R.id.playerNameList);
         convertView.setTag(holder);
      } else {
         holder = (ViewHolder) convertView.getTag();
      }
      holder.checkBox.setText("Checkbox " + position);
      holder.tvPlayer.setText(modelArrayList.get(position).getPlayer());
      holder.checkBox.setChecked(modelArrayList.get(position).getSelected());
      holder.checkBox.setTag(R.integer.btnPlusView, convertView);
      holder.checkBox.setTag(position);
      holder.checkBox.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            Integer pos = (Integer) holder.checkBox.getTag();
            Toast.makeText(context, "Checkbox " +pos+ "Clicked!",
            Toast.LENGTH_SHORT).show();
            if (modelArrayList.get(pos).getSelected()) {
               modelArrayList.get(pos).setSelected(false);
            } else {
               modelArrayList.get(pos).setSelected(true);
            }
         }
      });
      return convertView;
   }
   private class ViewHolder {
      CheckBox checkBox;
      private TextView tvPlayer;
   }
}

步驟 4 - 建立一個 Java 類(Model.java)並新增以下程式碼 -

class Model {
   private boolean isSelected;
   private String player;
   String getPlayer() {
      return player;
   }
   void setPlayer(String player) {
      this.player = player;
   }
   boolean getSelected() {
      return isSelected;
   }
   void setSelected(boolean selected) {
      isSelected = selected;
   }
}

步驟 5 - 在 res/values/strings.xml 中新增以下程式碼

<resources>
   <string name="app_name">Sample</string>
   <integer name="btnPlusView">1</integer>
   <integer name="btnPlusPos">2</integer>
</resources>

步驟 6 - 為您的 ListView 建立一個佈局(listItem.xml)並新增以下程式碼 -

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="horizontal" android:layout_width="match_parent"
   android:layout_height="match_parent">
   <CheckBox
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/checkBox" />
      <TextView
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:id="@+id/playerNameList"
         android:layout_marginStart="20dp"
         android:textSize="20sp" />
</LinearLayout>

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

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
   private ListView listView;
   private ArrayList<Model> modelArrayList;
   private CustomAdapter customAdapter;
   Button btnSelect, btnDeselect;
   public static String[] playerList = new String[]{"Sunil Chetri - INDIA",
      "Cristiano Ronaldo - Portugal",
      "Lionel Messi - Argentina",
      "Neymar Jr - Brazil",
      "Eden Hazard - Belgium",
      "Gigi Buffon - Italy",
      "James Rodrigues - Columbia",
      "Sadio Mane - Senegal",
      "Toni Kroos - Germany"};
      @Override
      protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);
         listView = findViewById(R.id.listView);
         btnSelect = findViewById(R.id.viewCheckedItem);
         btnDeselect = findViewById(R.id.deSelect);
         modelArrayList = getModel(false);
         customAdapter = new CustomAdapter(MainActivity.this, modelArrayList);
         listView.setAdapter(customAdapter);
         btnSelect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               modelArrayList = getModel(true);
               customAdapter = new CustomAdapter(MainActivity.this, modelArrayList);
               listView.setAdapter(customAdapter);
               Toast.makeText(getApplicationContext(), "Checked all items",
               Toast.LENGTH_SHORT).show();
            }
         });
         btnDeselect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               modelArrayList = getModel(false);
               customAdapter = new CustomAdapter(MainActivity.this,modelArrayList);
               listView.setAdapter(customAdapter);
               Toast.makeText(getApplicationContext(), "Unchecked all items",
               Toast.LENGTH_SHORT).show();
            }
         });
      }
      private ArrayList<Model> getModel(boolean isSelect) {
         ArrayList<Model>list = new ArrayList<>();
         for (int i = 0; i < 9; i++) {
            Model model = new Model();
            model.setSelected(isSelect);
            model.setPlayer(playerList[i]);
            list.add(model);
         }
         return list;
      }
   }

步驟 8 - 將以下程式碼新增到 androidManifest.xml 中

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="app.com.sample">
   <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 執行應用程式,請開啟您專案中的一個 activity 檔案,然後單擊工具欄中的執行播放圖示 圖示。選擇您的移動裝置作為選項,然後檢查您的移動裝置,它將顯示您的預設螢幕 -

更新於:2020年7月7日

2K+ 次瀏覽

啟動您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.