Я использую радиообъектив в адаптере listview, я хочу, чтобы выбрать/отменить выбор радиообъектива, на который я нажимаю.Как выбрать/снять флажок RadioButton из адаптера массива ListView в android
ответ
Сохраните состояние переключателя в списке или если есть только один выбор, в этом случае вы можете сохранить определенную позицию в переменной int и обновить значение переменной при выборе после этого, сделав adapter.notifyDataSetChanged()
. Вам нужно написать код в getView
, чтобы отразить изменения.
Грубый пример: (Я стар, чтобы ListView (проверить recyclerview) сейчас, но ваш adpater должен выглядеть следующим образом)
Adapter{
int selectedPosition = -1; // initially nothing selected
getView(..,..., int position){
if(selectedPosition==position){
holder.radioButton.setChecked(true);
}else{
holder.radioButton.setChecked(false);
}
holder.radioButton.setTag(position);
holder.radioButton.onClick(){
selectedPosition = (Integer)holder.radioButton.getTag();
notifyDataSetChanged();
}
)
static class Holder {
RadioButton radioButton;
}
Thnx для ответа. можете ли вы рассказать мне код? – Shivangi
@Shivangi проверить обновленный ответ – Spartan
ya Я пробовал это, но он выбирает только один радиообъект за раз, но я хочу, когда пользователь нажимает на любую радиометку элемента списка, которую он может выбрать, и при нажатии на тот же переключатель снова он должен быть отменен. – Shivangi
Добавить clickListener в radionButton, так что если вы нажмете на RadioButton будет отменяете выбор, если он выбран. (По умолчанию он будет проверяться по щелчку, если он не установлен)
radioButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
if (radioButton.isChecked()) {
radioButton.setChecked(false);
}
}
});
На этом этапе Во-первых, мы получаем ссылку на Button
и ListView
. После этого мы создаем массив String для вопросов, а затем установите adapter
для заполнения данных в ListView
. Наконец, мы выполняем событие setOnClickListener
на Button
, поэтому всякий раз, когда пользователь нажимает на Button
, ответы на вопросы отображаются с помощью Toast
.
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
ListView simpleList;
String[] questions;
Button submit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get the string array from string.xml file
questions = getResources().getStringArray(R.array.questions);
// get the reference of ListView and Button
simpleList = (ListView) findViewById(R.id.simpleListView);
submit = (Button) findViewById(R.id.submit);
// set the adapter to fill the data in the ListView
CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), questions);
simpleList.setAdapter(customAdapter);
// perform setOnClickListerner event on Button
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String message = "";
// get the value of selected answers from custom adapter
for (int i = 0; i < CustomAdapter.selectedAnswers.size(); i++) {
message = message + "\n" + (i + 1) + " " + CustomAdapter.selectedAnswers.get(i);
}
// display the message on screen with the help of Toast.
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
In this step we create a custom adapter class and extends BaseAdapter in this class. In this step we firstly set the data in the list and then perform setOnCheckedChangeListener event on RadioButton.
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.TextView;
import java.util.ArrayList;
public class CustomAdapter extends BaseAdapter {
Context context;
String[] questionsList;
LayoutInflater inflter;
public static ArrayList<String> selectedAnswers;
public CustomAdapter(Context applicationContext, String[] questionsList) {
this.context = context;
this.questionsList = questionsList;
// initialize arraylist and add static string for all the questions
selectedAnswers = new ArrayList<>();
for (int i = 0; i < questionsList.length; i++) {
selectedAnswers.add("Not Attempted");
}
inflter = (LayoutInflater.from(applicationContext));
}
@Override
public int getCount() {
return questionsList.length;
}
@Override
public Object getItem(int i) {
return null;
}
@Override
public long getItemId(int i) {
return 0;
}
@Override
public View getView(final int i, View view, ViewGroup viewGroup) {
view = inflter.inflate(R.layout.list_items, null);
// get the reference of TextView and Button's
TextView question = (TextView) view.findViewById(R.id.question);
RadioButton yes = (RadioButton) view.findViewById(R.id.yes);
RadioButton no = (RadioButton) view.findViewById(R.id.no);
// perform setOnCheckedChangeListener event on yes button
yes.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// set Yes values in ArrayList if RadioButton is checked
if (isChecked)
selectedAnswers.set(i, "Yes");
}
});
// perform setOnCheckedChangeListener event on no button
no.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// set No values in ArrayList if RadioButton is checked
if (isChecked)
selectedAnswers.set(i, "No");
}
});
// set the value in TextView
question.setText(questionsList[i]);
return view;
}
}
Эй, у меня есть ListView, и в соответствии с потребностями пользователя пользователь может добавить столько данных, сколько потребуется, и выбрать или отменить выбор элемента списка в соответствии с его щелчком – Shivangi
Эй @ Шиванги, сколько радиокнопки в вашем элементе списка? –
Это зависит от пользователя, количества элементов, которые он добавляет в listview, поэтому радиолюбители не исправить – Shivangi
radiogroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// Radio button
RadioButton rb1=(RadioButton)findViewById(R.id.rdb1);
if (rb1.isChecked()){
Toast.makeText(MainActivity.this, "1 option selected", Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(MainActivity.this, "2 option selected", Toast.LENGTH_LONG).show();
}
}
});
что вы пробовали? и обмениваться некоторыми кодами –
okey, я пытаюсь использовать переключатель в классе адаптера, но я не могу проверить/снять отметку с переключателя, если когда-то проверяется. – Shivangi
предоставил ответ ниже. –