我希望您在以下方面为我提供帮助。 我有一个带有5个recyclerView和RadioGroup替代品的图像。 如何获得用户在每个图像的单选按钮中所做的选择? 然后我通过java和xml代码。
代码类Anime.java
public class Anime {
private int imagen;
public Anime(int imagen) {
this.imagen = imagen;
}
public int getImagen() {
return imagen;
}
}
代码AnimeAdapter.java
public class AnimeAdapter extends RecyclerView.Adapter<AnimeAdapter.AnimeViewHolder> {
private List<Anime> items;
public static class AnimeViewHolder extends RecyclerView.ViewHolder {
// Campos respectivos de un item
public ImageView imagen;
private RadioGroup group;
private int ids_respuestas[] =
{R.id.respuesta1, R.id.respuesta2, R.id.respuesta3, R.id.respuesta4, R.id.respuesta5};
public AnimeViewHolder(View v) {
super(v);
imagen = v.findViewById(R.id.imagen);
group = v.findViewById(R.id.answer_group);
}
}
public AnimeAdapter(List<Anime> items) {
this.items = items;
}
@Override
public int getItemCount() {
return items.size();
}
@Override
public AnimeViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.anime_card, viewGroup, false);
return new AnimeViewHolder(v);
}
@Override
public void onBindViewHolder(AnimeViewHolder viewHolder, int i) {
viewHolder.imagen.setImageResource(items.get(i).getImagen());
}
}
代码Activity.java
public class ThirdActivity extends AppCompatActivity {
//Declarar instancias globales
private RecyclerView recycler;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager lManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
// Inicializar Animes
List<Anime> items = new ArrayList<>();
items.add(new Anime(R.drawable.angel));
items.add(new Anime(R.drawable.death));
items.add(new Anime(R.drawable.fate));
items.add(new Anime(R.drawable.nhk));
items.add(new Anime(R.drawable.suzumiya));
// Obtener el Recycler
recycler = findViewById(R.id.reciclador);
//recycler.setHasFixedSize(true);
// Usar un administrador para LinearLayout
lManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL,false);
recycler.setLayoutManager(lManager);
// Crear un nuevo adaptador
adapter = new AnimeAdapter(items);
recycler.setAdapter(adapter);
}
public void result(View view) {
}
}
答案 0 :(得分:1)
要获取选择,您可以在onBindViewHolder
holder.selectionState.setChecked(lastSelectedPosition == position);
以及此代码在您的ViewHolder
selectionState.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
lastSelectedPosition = getAdapterPosition();
notifyDataSetChanged();
Toast.makeText(OffersRecyclerViewAdapter.this.context,
"selected offer is " + offerName.getText(),
Toast.LENGTH_LONG).show();
}
});
希望它会为您提供帮助