📜  如何在 Android RecyclerView 中选择单个 RadioButton?

📅  最后修改于: 2022-05-13 01:54:37.144000             🧑  作者: Mango

如何在 Android RecyclerView 中选择单个 RadioButton?

RecyclerView 是作为 GridView 和 ListView 的继承者添加到 android studio 中的 ViewGroup。这是对两者的改进,可以在最新的 v-7 支持包中找到。它的创建是为了可以将任何具有 XML 布局的列表构建为可以大量定制的项目,同时提高 ListViews 和 GridViews 的效率。在本文中,我们将了解如何在处理 RecyclerView 时选择单个 RadioButton。

我们将在本文中构建什么?

这是我们将在此应用程序中构建的示例视频。请注意,我们将使用Java语言来制作这个项目。

分步实施

第 1 步:创建一个新项目

  • 打开一个新项目。
  • 我们将使用Java语言开发 Empty Activity。保持所有其他选项不变。
  • 在您方便的时候命名应用程序。
  • 将有两个名为 activity_main.xml 和 MainActivity 的默认文件。Java

如果您不知道如何在 Android Studio 中创建新项目,可以参考如何在 Android Studio 中创建/启动新项目?

步骤 2. 添加所需的依赖项

导航到 Gradle Scripts > gradle.scripts(module) 并添加以下依赖项

implementation 'com.google.android.material:material:1.3.0'

步骤 3. 处理 XML 文件

导航到 app > res > layout > activity_main.xml 并将以下代码添加到该文件。下面是 activity_main.xml 文件的代码。

XML


  
    
  


XML




Java
package com.example.singleradiobuttonrv;
  
import android.os.Bundle;
import android.service.autofill.LuhnChecksumValidator;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
  
public class MainActivity extends AppCompatActivity {
    // Initialize variable
    RecyclerView recyclerView;
    ItemClickListener itemClickListener;
    MainAdapter adapter;
  
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // Assign variable
        recyclerView = findViewById(R.id.recycler_view);
  
        // initialize array list
        ArrayList arrayList = new ArrayList<>();
        
        // Use for loop
        for (int i = 0; i < 20; i++) {
            // add values in array list
            arrayList.add("RB " + i);
        }
  
        // Initialize listener
        itemClickListener = new ItemClickListener() {
            @Override public void onClick(String s)
            {
                // Notify adapter
                recyclerView.post(new Runnable() {
                    @Override public void run()
                    {
                        adapter.notifyDataSetChanged();
                    }
                });
                // Display toast
                Toast
                    .makeText(getApplicationContext(),
                              "Selected : " + s,
                              Toast.LENGTH_SHORT)
                    .show();
            }
        };
  
        // Set layout manager
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
  
        // Initialize adapter
        adapter = new MainAdapter(arrayList, itemClickListener);
  
        // set adapter
        recyclerView.setAdapter(adapter);
    }
}


Java
package com.example.singleradiobuttonrv;
  
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.AdapterListUpdateCallback;
import androidx.recyclerview.widget.RecyclerView;
import java.io.*;
import java.util.ArrayList;
  
public class MainAdapter
    extends RecyclerView.Adapter {
  
    // Initialize variable
    ArrayList arrayList;
    ItemClickListener itemClickListener;
    int selectedPosition = -1;
  
    // Create constructor
    public MainAdapter(ArrayList arrayList,
                       ItemClickListener itemClickListener)
    {
        this.arrayList = arrayList;
        this.itemClickListener = itemClickListener;
    }
  
    @NonNull
    @Override
    public ViewHolder
    onCreateViewHolder(@NonNull ViewGroup parent,
                       int viewType)
    {
        // Initialize view
        View view = LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.item_main, parent,
                                 false);
        // Pass holder view
        return new ViewHolder(view);
    }
  
    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder,
                                 int position)
    {
        // Set text on radio button
        holder.radioButton.setText(arrayList.get(position));
        
        // Checked selected radio button
        holder.radioButton.setChecked(position
                                      == selectedPosition);
  
        // set listener on radio button
        holder.radioButton.setOnCheckedChangeListener(
            new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(
                    CompoundButton compoundButton,
                    boolean b)
                {
                    // check condition
                    if (b) {
                        // When checked
                        // update selected position
                        selectedPosition
                            = holder.getAdapterPosition();
                        // Call listener
                        itemClickListener.onClick(
                            holder.radioButton.getText()
                                .toString());
                    }
                }
            });
    }
  
    @Override public long getItemId(int position)
    {
        // pass position
        return position;
    }
    @Override public int getItemViewType(int position)
    {
        // pass position
        return position;
    }
  
    @Override public int getItemCount()
    {
        // pass total list size
        return arrayList.size();
    }
  
    public class ViewHolder
        extends RecyclerView.ViewHolder {
        // Initialize variable
        RadioButton radioButton;
  
        public ViewHolder(@NonNull View itemView)
        {
            super(itemView);
  
            // Assign variable
            radioButton
                = itemView.findViewById(R.id.radio_button);
        }
    }
}
  
class GFG {
    public static void main(String[] args)
    {
        System.out.println("GFG!");
    }
}


Java
package com.example.singleradiobuttonrv;
  
public interface ItemClickListener {
    // Create method
    void onClick(String s);
}


导航到应用 > res > 布局 > 右键单击 > 新建 > 布局资源文件并将其命名为 item_main.xml。在 item_main.xml 文件中使用以下代码 -

XML




第 4 步:处理Java文件

导航到 MainActivity。 Java文件并在其中使用以下代码。代码中添加了注释以便更好地理解。

Java

package com.example.singleradiobuttonrv;
  
import android.os.Bundle;
import android.service.autofill.LuhnChecksumValidator;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
  
public class MainActivity extends AppCompatActivity {
    // Initialize variable
    RecyclerView recyclerView;
    ItemClickListener itemClickListener;
    MainAdapter adapter;
  
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // Assign variable
        recyclerView = findViewById(R.id.recycler_view);
  
        // initialize array list
        ArrayList arrayList = new ArrayList<>();
        
        // Use for loop
        for (int i = 0; i < 20; i++) {
            // add values in array list
            arrayList.add("RB " + i);
        }
  
        // Initialize listener
        itemClickListener = new ItemClickListener() {
            @Override public void onClick(String s)
            {
                // Notify adapter
                recyclerView.post(new Runnable() {
                    @Override public void run()
                    {
                        adapter.notifyDataSetChanged();
                    }
                });
                // Display toast
                Toast
                    .makeText(getApplicationContext(),
                              "Selected : " + s,
                              Toast.LENGTH_SHORT)
                    .show();
            }
        };
  
        // Set layout manager
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
  
        // Initialize adapter
        adapter = new MainAdapter(arrayList, itemClickListener);
  
        // set adapter
        recyclerView.setAdapter(adapter);
    }
}

导航到应用 > 右键单击 > 新建 > Java类并将其命名为 MainAdapter。Java在其中使用以下代码。代码中添加了注释以便更好地理解。

Java

package com.example.singleradiobuttonrv;
  
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.AdapterListUpdateCallback;
import androidx.recyclerview.widget.RecyclerView;
import java.io.*;
import java.util.ArrayList;
  
public class MainAdapter
    extends RecyclerView.Adapter {
  
    // Initialize variable
    ArrayList arrayList;
    ItemClickListener itemClickListener;
    int selectedPosition = -1;
  
    // Create constructor
    public MainAdapter(ArrayList arrayList,
                       ItemClickListener itemClickListener)
    {
        this.arrayList = arrayList;
        this.itemClickListener = itemClickListener;
    }
  
    @NonNull
    @Override
    public ViewHolder
    onCreateViewHolder(@NonNull ViewGroup parent,
                       int viewType)
    {
        // Initialize view
        View view = LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.item_main, parent,
                                 false);
        // Pass holder view
        return new ViewHolder(view);
    }
  
    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder,
                                 int position)
    {
        // Set text on radio button
        holder.radioButton.setText(arrayList.get(position));
        
        // Checked selected radio button
        holder.radioButton.setChecked(position
                                      == selectedPosition);
  
        // set listener on radio button
        holder.radioButton.setOnCheckedChangeListener(
            new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(
                    CompoundButton compoundButton,
                    boolean b)
                {
                    // check condition
                    if (b) {
                        // When checked
                        // update selected position
                        selectedPosition
                            = holder.getAdapterPosition();
                        // Call listener
                        itemClickListener.onClick(
                            holder.radioButton.getText()
                                .toString());
                    }
                }
            });
    }
  
    @Override public long getItemId(int position)
    {
        // pass position
        return position;
    }
    @Override public int getItemViewType(int position)
    {
        // pass position
        return position;
    }
  
    @Override public int getItemCount()
    {
        // pass total list size
        return arrayList.size();
    }
  
    public class ViewHolder
        extends RecyclerView.ViewHolder {
        // Initialize variable
        RadioButton radioButton;
  
        public ViewHolder(@NonNull View itemView)
        {
            super(itemView);
  
            // Assign variable
            radioButton
                = itemView.findViewById(R.id.radio_button);
        }
    }
}
  
class GFG {
    public static void main(String[] args)
    {
        System.out.println("GFG!");
    }
}

创建一个新接口并将其命名为 ItemClickListener。在 ItemClickListener 中使用以下代码。 Java文件——

Java

package com.example.singleradiobuttonrv;
  
public interface ItemClickListener {
    // Create method
    void onClick(String s);
}

这是我们应用程序的最终输出。

输出: