Shivangi Shivangi - 3 months ago 137
Android Question

When scroll in Recyler View Radio Button changes its selection

I am using RecylerView to set RadioButton.But on selection selected changes its position when scroll.Please help me.

Thanx in advance!!!


My RecylerView Layout

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.RecyclerView
android:id="@+id/dummy_recycle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
</android.support.v7.widget.RecyclerView>


</RelativeLayout>


My RadioButton Layout

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="wrap_content"
android:orientation="vertical"
android:layout_height="wrap_content">
<RadioButton
android:id="@+id/radio_dummy"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>

</LinearLayout>
</RelativeLayout>


My RecylerView Java File

public class Dummy extends AppCompatActivity {
ArrayList<String> arr_qty;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dummy);
arr_qty=new ArrayList<>();
for(int i =0;i<50;i++){
arr_qty.add(String.valueOf(i));

}
RecyclerView dummy = (RecyclerView)findViewById(R.id.dummy_recycle);
DummyAdapter adapter = new DummyAdapter(getApplicationContext(), arr_qty);
dummy.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false));
dummy.setAdapter(adapter);
}
}


My RecylerView Adapter

public class DummyAdapter extends RecyclerView.Adapter<DummyAdapter.MyViewHolder>{
private Context c;
ArrayList<String> arr=new ArrayList<>();
public DummyAdapter(Context context, ArrayList<String> arr_qty) {
this.arr = arr_qty;
this.c = context;

}

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.dummy_value, parent, false);
return new MyViewHolder(view);
}

@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
}

@Override
public int getItemCount() {
return arr.size();
}

public class MyViewHolder extends RecyclerView.ViewHolder {
public RadioButton radio;
public MyViewHolder(View itemView) {
super(itemView);
radio = (RadioButton) itemView.findViewById(R.id.radio_dummy);
}
}
}

Answer

In Recycleview adapter you can add below line. It's already working for my code. This code set your list position fix. It's working for my code.

public int getItemViewType(int position) {
        return position;
    }