2013-04-18 2 views
5

Я снова и снова задавал вопрос, есть много вопросов, которые я нашел в stackoverflow, но у меня не было решения. Вот моя проблема. У меня есть список пункта в LinearLayout, как это: enter image description hereВыберите только одну радиокнопку из списка.

Когда экран приходит первым, кнопка последней радионы выбирается автоматически. Но если я выберу другую радиокнопку, последняя радиокнопка уже находится в выбранном состоянии. Я хочу выбрать только одну кнопку радиона, но в то же время, когда на экране появляется первый, последняя радиокнопка будет автоматически выбрана, а другая автоматически не будет выбрана. Как я могу это достичь. Мой класс адаптер:

public class AdapterPaymentMethod extends ArrayAdapter<PaymentData> { 
    private Context context; 
    private boolean userSelected = false; 
    ViewHolder holder; 

    public AdapterPaymentMethod(Context context, int resource, 
      List<PaymentData> items) { 
     super(context, resource, items); 
     this.context = context; 
    } 

    /* private view holder class */ 
    private class ViewHolder { 
     RadioButton radioBtn; 
     Button btPaymentMethod; 
     // ImageView ivLine; 
    } 

    public View getView(final int position, View convertView, ViewGroup parent) { 
     holder = null; 
     PaymentData rowItem = getItem(position); 
     LayoutInflater mInflater = (LayoutInflater) context 
       .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     if (convertView == null) { 
      convertView = mInflater.inflate(
        com.android.paypal.homeactivity.R.layout.list_item, null); 
      holder = new ViewHolder(); 
      holder.radioBtn = (RadioButton) convertView 
        .findViewById(com.android.paypal.homeactivity.R.id.rdb_payment_method); 
      holder.btPaymentMethod = (Button) convertView 
        .findViewById(com.android.paypal.homeactivity.R.id.bt_item_event); 
      convertView.setTag(holder); 
     } else 
      holder = (ViewHolder) convertView.getTag(); 

     if(position==getCount()-1 && userSelected==false){ 
      holder.radioBtn.setChecked(true); 
     Log.d("if position", ""+position); 
     } 
     else{ 
      holder.radioBtn.setChecked(false); 
      Log.d("else position", ""+position); 
     } 

     holder.radioBtn.setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       userSelected=true; 
       if(getCount()-1==position&&userSelected==true){   
       } 
       else if(getCount()-2==position&&userSelected==true) 
       { 
        holder.radioBtn.setChecked(true); 
       } 
      } 
     }); 



     holder.radioBtn.setText(rowItem.getRdbText()); 
     holder.btPaymentMethod.setText(rowItem.getBtText()); 
     return convertView; 
    } 
} 
+0

им также застрял на тех же вопросов, может у меня помочь, но в флажком –

ответ

13

Держите в настоящее время проверяется RadioButton в переменной в вашем Activity. В OnClickListener вашей RadioButtons сделать это:

// checks if we already have a checked radiobutton. If we don't, we can assume that 
// the user clicked the current one to check it, so we can remember it. 
if(mCurrentlyCheckedRB == null) 
    mCurrentlyCheckedRB = (RadioButton) v; 
    mCurrentlyCheckedRB.setChecked(true); 
} 

// If the user clicks on a RadioButton that we've already stored as being checked, we 
// don't want to do anything.  
if(mCurrentlyCheckedRB == v) 
    return; 

// Otherwise, uncheck the currently checked RadioButton, check the newly checked 
// RadioButton, and store it for future reference. 
mCurrentlyCheckedRB.setChecked(false); 
((RadioButton)v).setChecked(true); 
mCurrentlyCheckedRB = (RadioButton)v; 
+0

Ваше решение отлично работает. Можете ли вы объяснить свой код. Я не понял ваш код. Я новичок. Благодарю. – androidcodehunter

+1

Я добавил несколько комментариев, чтобы объяснить это. Если это сработает для вас, пожалуйста, установите ответ как принято! – Catherine

+1

Спасибо за ваше объяснение. Я люблю это. – androidcodehunter

5

Вот мой код:

ListAdapter.java

public class ListAdapter extends BaseAdapter { 

    private Context context; 
    private String[] version; 
    private LayoutInflater inflater; 
    private RadioButton selected = null; 

    public ListAdapter(Context context, String[] version) { 
     this.context = context; 
     this.version = version; 
     inflater = LayoutInflater.from(context); 
    } 

    @Override 
    public int getCount() { 
     return version.length; 
    } 

    @Override 
    public Object getItem(int position) { 
     return version; 
    } 

    @Override 
    public long getItemId(int position) { 
     return position; 
    } 

    @Override 
    public View getView(final int position, View view, ViewGroup viewGroup) { 

     final Holder holder; 
     if (view == null) { 
      holder = new Holder(); 
      view = inflater.inflate(R.layout.row_list, null); 

      holder.radioButton = (RadioButton) view.findViewById(R.id.radio1); 
      holder.textViewVersion = (TextView) view.findViewById(R.id.textView1); 
      holder.btnMore = (Button) view.findViewById(R.id.button1); 

      view.setTag(holder); 
     } else { 
      holder = (Holder) view.getTag(); 
     } 

     holder.textViewVersion.setText(version[position]); 

     //by default last radio button selected 
     if (position == getCount() - 1) { 
      if (selected == null) { 
       holder.radioButton.setChecked(true); 
       selected = holder.radioButton; 
      } 
     } 

     holder.radioButton.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 

       if (selected != null) { 
        selected.setChecked(false); 
       } 
       holder.radioButton.setChecked(true); 
       selected = holder.radioButton; 
      } 
     });  
    } 

    private class Holder { 
     private RadioButton radioButton; 
     private TextView textViewVersion; 
     private Button btnMore; 
    } 
} 

Надеется, что это помогает :)

+0

Спасибо .. вы за жизнь! :) –

0

Попробуйте этот хак.

В макете это изменяется.

<RadioButton 
    android:id="@+id/radio" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_gravity="center_vertical" 
    **android:clickable="false" 
    android:focusable="false"** 
/> 

В вашем адаптере добавьте эти строки:

private int selectedPosition = -1; 

viewHolder.choiceButton = (RadioButton)convertView.findViewById(R.id.radio); 

if(selectedPosition == -1) { 
    viewHolder.choiceButton.setChecked(position==getCount()-1); 
} 
else{ 
    viewHolder.choiceButton.setChecked(selectedPosition == position); 
} 

В GetView() назначить SelectedPosition:

viewHolder.clickLayout.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       selectedPosition = (int) view.getTag(); 
       notifyDataSetChanged(); 
      } 
     }); 
+0

Этот код не работает. Выбирается несколько переключателей. –

+1

Вы назначили selectedPosition на макет клика с помощью getTag()? –

Смежные вопросы