RadioGroup not working in fragment android - android

I have faced an issue radio check change listener not working in the android fragment, I tried this within an activity it will work fine, while I convert into fragment it will give no response, please help me, here is my code.
K06_Away.java
public class K06_Away extends Fragment {
private View kf06_view;
protected Typeface tfLatoBold,tfLatoMedium,tfLatoRegular;
private Button button_kf06_back,button_kf06_next;
private TextView txtVw_kf06_resident_away;
private EditText edTxt_kf06_visiting_lastname;
private RadioGroup radioGp_kf06_resident_away;
List<RadioButton> radioButtons = new ArrayList<RadioButton>();
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
kf06_view = inflater.inflate(R.layout.k06_away, container, false);
return kf06_view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
configViews();
}
private void configViews() {
button_kf06_back = (Button) kf06_view.findViewById(R.id.button_kf06_back);
button_kf06_next = (Button) kf06_view.findViewById(R.id.button_kf06_next);
txtVw_kf06_resident_away= (TextView) kf06_view.findViewById(R.id.txtVw_kf06_resident_away);
radioGp_kf06_resident_away = (RadioGroup) kf06_view.findViewById(R.id.radioGp_kf06_resident_away);
radioButtons.add( (RadioButton)kf06_view.findViewById(R.id.radio_kf06_1_2_hours) );
radioButtons.add( (RadioButton)kf06_view.findViewById(R.id.radio_kf06_halfday) );
radioButtons.add( (RadioButton)kf06_view.findViewById(R.id.radio_kf06_allday) );
radioButtons.add( (RadioButton)kf06_view.findViewById(R.id.radio_kf06_moreday) );
configClickListeners();
radioButtonAction();
}
private void configClickListeners() {
button_kf06_back.setOnClickListener(this);
button_kf06_next.setOnClickListener(this);
}
private void radioButtonAction(){
for (RadioButton button : radioButtons){
button.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) processRadioButtonClick(buttonView);
String radio_Text = buttonView.getText().toString();
int radio_Id = buttonView.getId();
System.out.println("Selected the Radio:"+radio_Text+", Radio-Id:"+radio_Id);
}
});
}
}
private void processRadioButtonClick(CompoundButton buttonView){
for (RadioButton button : radioButtons){
if (button != buttonView ) button.setChecked(false);
}
}
}
k06_away.xml
<RadioGroup
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/lLayout_kf06_resident_away"
android:id="#+id/radioGp_kf06_resident_away">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:baselineAligned="false"
tools:ignore="UselessParent">
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="vertical"
android:layout_marginLeft="150dp"
tools:ignore="RtlHardcoded">
<RadioButton
android:id="#+id/radio_kf06_1_2_hours"
style="#style/radionbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/label_resident_away_hour_1"
android:layout_gravity="left"
android:checked="false"
android:textSize="25sp"
android:paddingStart="20dp"
android:layout_marginTop="150dp"
android:textColor="#color/colorWhite"
tools:ignore="NestedWeights,RtlSymmetry" />
<RadioButton
android:id="#+id/radio_kf06_halfday"
style="#style/radionbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/label_resident_away_hour_2"
android:layout_gravity="left"
android:checked="false"
android:textSize="25sp"
android:textColor="#color/colorWhite"
android:paddingStart="20dp"
android:layout_marginTop="50dp"
tools:ignore="NestedWeights,RtlSymmetry"/>
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="vertical"
android:layout_marginLeft="50dp"
tools:ignore="RtlHardcoded">
<RadioButton
android:id="#+id/radio_kf06_allday"
style="#style/radionbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/label_resident_away_hour_3"
android:layout_gravity="left"
android:checked="false"
android:textSize="25sp"
android:textColor="#color/colorWhite"
android:paddingStart="20dp"
android:layout_marginTop="150dp"
tools:ignore="NestedWeights,RtlSymmetry"/>
<RadioButton
android:id="#+id/radio_kf06_moreday"
style="#style/radionbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/label_resident_away_hour_4"
android:layout_gravity="left"
android:checked="false"
android:textSize="25sp"
android:textColor="#color/colorWhite"
android:paddingStart="20dp"
android:layout_marginTop="50dp"
tools:ignore="NestedWeights,RtlSymmetry,RtlHardcoded"/>
</LinearLayout>
</LinearLayout>
</RadioGroup>

1. Try to call method configViews() from onCreateView() and pass the view kf06_view as parameter.
2. Implement View.OnClickListener to handle button_kf06_back and button_kf06_next click events.
Update your K06_Away Fragment as below:
public class K06_Away extends Fragment implements View.OnClickListener {
protected Typeface tfLatoBold,tfLatoMedium,tfLatoRegular;
private Button button_kf06_back,button_kf06_next;
private TextView txtVw_kf06_resident_away;
private EditText edTxt_kf06_visiting_lastname;
private RadioGroup radioGp_kf06_resident_away;
List<RadioButton> radioButtons = new ArrayList<RadioButton>();
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View kf06_view = inflater.inflate(R.layout.k06_away, container, false);
// Init
configViews(kf06_view);
return kf06_view;
}
private void configViews(View view) {
button_kf06_back = (Button) view.findViewById(R.id.button_kf06_back);
button_kf06_next = (Button) view.findViewById(R.id.button_kf06_next);
txtVw_kf06_resident_away= (TextView) view.findViewById(R.id.txtVw_kf06_resident_away);
radioGp_kf06_resident_away = (RadioGroup) view.findViewById(R.id.radioGp_kf06_resident_away);
radioButtons.add( (RadioButton) view.findViewById(R.id.radio_kf06_1_2_hours) );
radioButtons.add( (RadioButton) view.findViewById(R.id.radio_kf06_halfday) );
radioButtons.add( (RadioButton) view.findViewById(R.id.radio_kf06_allday) );
radioButtons.add( (RadioButton) view.findViewById(R.id.radio_kf06_moreday) );
configClickListeners();
radioButtonAction();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_kf06_back:
// Do something...
break;
case R.id.button_kf06_next:
// Do something...
break;
}
}
private void configClickListeners() {
button_kf06_back.setOnClickListener(this);
button_kf06_next.setOnClickListener(this);
}
private void radioButtonAction(){
for (RadioButton button : radioButtons){
button.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) processRadioButtonClick(buttonView);
String radio_Text = buttonView.getText().toString();
int radio_Id = buttonView.getId();
System.out.println("Selected the Radio:"+radio_Text+", Radio-Id:"+radio_Id);
}
});
}
}
private void processRadioButtonClick(CompoundButton buttonView){
for (RadioButton button : radioButtons){
if (button != buttonView ) button.setChecked(false);
}
}
}

RadioGroup Directly contain only RadioButtons,No other Layouts,if you add LinearLayout inside RadioGroup,it will not works as you expect.Only use RadioButtons as child of RadioGroup.

Related

Adding * and # key to the soft keyboard

1) PROBLEM:
I have an EditText in which the user has to enter USSD code.
Problem is, for entering USSD code the user has to switch to symbol keyboard (two to three times) which creates a very bad user experience.
USSD Code Examples: *345*77#, *333*25#, *123*678# etc.
<EditText
android:id="#+id/field_code"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:imeActionId="#integer/imo_action_search"
android:imeOptions="actionSearch"
android:inputType="phone" />
2) What I need:
How can I replace the highlighted buttons (below image) with * and # buttons without using a custom keyboard?
3) What I have tried!!!
1) All InputTypes for EditText.
2) Google the issue, the only solution I have found is a custom keyboard but I want to know is there any simple solution.
Each keyboard app has its own layout and you can't change it. For example android:inputType="phone" has different layouts on Gboard and SwiftKey.
Solution:
You should implement a custom InAppKeyboard and show it to the user instead of the system keyboard."Creating an In-App Keyboard for your Android Apps" is a good tutorial that describes how to develop a custom InAppKeyboard like this but you can design your desired layout and use it in your app easily.
Update:
For Using InAppKeyboard with dialog, I have an idea. I developed a custom DialogFragment which has 2 parts: 1. The dialog content part2. The custom keyboard part named CustomKeyboardDialog.
You can extend this class and create your custom dialog. Both setContentView and findViewById methods are available and you can use them to manage your dialog UI. You must override onCreate method in your custom dialog implementation and call setContentView there. Then override onCreateView method, call findViewById there and find your EditText and attach it custom keyboard by calling attachToCustomKeyboard method.
CustomKeyboardDialog.java
public abstract class CustomKeyboardDialog extends DialogFragment {
private View mRootView;
private int mContentLayoutResID;
private View mContentView;
private CustomKeyboardView mCustomKeyboardView;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onStart() {
super.onStart();
Dialog dialog = getDialog();
if (dialog != null) {
dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
}
}
#Nullable
#Override
final public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
mRootView = inflater.inflate(R.layout.dialog_custom_keyboard, container, false);
ViewGroup contentViewContainer = mRootView.findViewById(R.id.content_view_container);
mContentView = inflater.inflate(mContentLayoutResID, contentViewContainer, true);
this.mCustomKeyboardView = mRootView.findViewById(R.id.keyboard_view);
this.onCreateView(mContentView);
return mRootView;
}
public View findViewById(int id) {
return mContentView.findViewById(id);
}
public void setContentView(#LayoutRes int layoutResID) {
this.mContentLayoutResID = layoutResID;
}
public void showKeyboard(InputConnection inputConnection) {
mCustomKeyboardView.setInputConnection(inputConnection);
mCustomKeyboardView.setVisibility(View.VISIBLE);
mCustomKeyboardView.animate().translationY(0).setListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animation) {
}
#Override
public void onAnimationEnd(Animator animation) {
updateContentViewSize(true);
}
#Override
public void onAnimationCancel(Animator animation) {
}
#Override
public void onAnimationRepeat(Animator animation) {
}
});
}
public void hideKeyboard() {
updateContentViewSize(false);
mCustomKeyboardView.animate().translationY(mCustomKeyboardView.getMeasuredHeight()).setListener(null);
}
private void updateContentViewSize(boolean keyboardVisible) {
ConstraintLayout.LayoutParams layoutParams = (ConstraintLayout.LayoutParams) mContentView.getLayoutParams();
if(keyboardVisible) {
layoutParams.bottomToTop = R.id.keyboard_view;
layoutParams.bottomToBottom = ConstraintLayout.LayoutParams.UNSET;
} else {
layoutParams.bottomToBottom = ConstraintLayout.LayoutParams.PARENT_ID;
layoutParams.bottomToTop = ConstraintLayout.LayoutParams.UNSET;
}
mContentView.setLayoutParams(layoutParams);
}
public void onCreateView(View contentView) {
}
#Override
public void onResume() {
super.onResume();
getDialog().setOnKeyListener(new DialogInterface.OnKeyListener()
{
#Override
public boolean onKey(android.content.DialogInterface dialog, int keyCode,android.view.KeyEvent event) {
if ((keyCode == android.view.KeyEvent.KEYCODE_BACK))
{
if(mCustomKeyboardView.getVisibility() == View.VISIBLE)
hideKeyboard();
return true;
}
else
return false;
}
});
}
#Override
public void onPause() {
super.onPause();
getDialog().setOnKeyListener(null);
}
public void attachToCustomKeyboard(EditText editText) {
editText.setShowSoftInputOnFocus(false);
editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
showKeyboard(editText.onCreateInputConnection(new EditorInfo()));
}
}
});
editText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showKeyboard(editText.onCreateInputConnection(new EditorInfo()));
}
});
}
public void detachFromCustomKeyboard(EditText editText) {
editText.setShowSoftInputOnFocus(true);
editText.setOnFocusChangeListener(null);
editText.setOnClickListener(null);
}
}
dialog_custom_keyboard.xml
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/content_view_container"
android:background="#android:color/transparent"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toTopOf="#id/keyboard_view"
android:orientation="vertical"
android:gravity="center">
</LinearLayout>
<mirm.test.testapp.dialog.CustomKeyboardView
android:id="#+id/keyboard_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
android:background="#eee"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
CustomKeyboardView.java
public class CustomKeyboardView extends LinearLayout implements View.OnClickListener {
private Button button1, button2, button3, button4,
button5, button6, button7, button8,
button9, button0, buttonDelete, buttonEnter, buttonSharp, buttonStar;
private SparseArray<String> keyValues = new SparseArray<>();
private InputConnection inputConnection;
public CustomKeyboardView(Context context) {
this(context, null, 0);
}
public CustomKeyboardView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CustomKeyboardView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
setOrientation(VERTICAL);
LayoutInflater.from(context).inflate(R.layout.custom_keyboard_layout, this, true);
button1 = (Button) findViewById(R.id.button_1);
button1.setOnClickListener(this);
button2 = (Button) findViewById(R.id.button_2);
button2.setOnClickListener(this);
button3 = (Button) findViewById(R.id.button_3);
button3.setOnClickListener(this);
button4 = (Button) findViewById(R.id.button_4);
button4.setOnClickListener(this);
button5 = (Button) findViewById(R.id.button_5);
button5.setOnClickListener(this);
button6 = (Button) findViewById(R.id.button_6);
button6.setOnClickListener(this);
button7 = (Button) findViewById(R.id.button_7);
button7.setOnClickListener(this);
button8 = (Button) findViewById(R.id.button_8);
button8.setOnClickListener(this);
button9 = (Button) findViewById(R.id.button_9);
button9.setOnClickListener(this);
button0 = (Button) findViewById(R.id.button_0);
button0.setOnClickListener(this);
buttonDelete = (Button) findViewById(R.id.button_delete);
buttonDelete.setOnClickListener(this);
buttonEnter = (Button) findViewById(R.id.button_enter);
buttonEnter.setOnClickListener(this);
buttonSharp = (Button) findViewById(R.id.button_sharp);
buttonSharp.setOnClickListener(this);
buttonStar = (Button) findViewById(R.id.button_star);
buttonStar.setOnClickListener(this);
keyValues.put(R.id.button_1, "1");
keyValues.put(R.id.button_2, "2");
keyValues.put(R.id.button_3, "3");
keyValues.put(R.id.button_4, "4");
keyValues.put(R.id.button_5, "5");
keyValues.put(R.id.button_6, "6");
keyValues.put(R.id.button_7, "7");
keyValues.put(R.id.button_8, "8");
keyValues.put(R.id.button_9, "9");
keyValues.put(R.id.button_0, "0");
keyValues.put(R.id.button_enter, "\n");
keyValues.put(R.id.button_sharp, "#");
keyValues.put(R.id.button_star, "*");
}
#Override
public void onClick(View view) {
if (inputConnection == null)
return;
if (view.getId() == R.id.button_delete) {
CharSequence selectedText = inputConnection.getSelectedText(0);
if (TextUtils.isEmpty(selectedText)) {
inputConnection.deleteSurroundingText(1, 0);
} else {
inputConnection.commitText("", 1);
}
} else {
String value = keyValues.get(view.getId());
inputConnection.commitText(value, 1);
}
}
public void setInputConnection(InputConnection ic) {
inputConnection = ic;
}
}
custom_keyboard_layout.xml
<merge xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/button_1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="1"/>
<Button
android:id="#+id/button_2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="2"/>
<Button
android:id="#+id/button_3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="3"/>
<Button
android:id="#+id/button_4"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="4"/>
<Button
android:id="#+id/button_5"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="5"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/button_6"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="6"/>
<Button
android:id="#+id/button_7"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="7"/>
<Button
android:id="#+id/button_8"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="8"/>
<Button
android:id="#+id/button_9"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="9"/>
<Button
android:id="#+id/button_0"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="0"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/button_sharp"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#"/>
<Button
android:id="#+id/button_star"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="*"/>
<Button
android:id="#+id/button_delete"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1.3"
android:text="Delete"/>
<Button
android:id="#+id/button_enter"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1.7"
android:text="Enter"/>
</LinearLayout>
</merge>
Here is an example of custom dialog implementation:
SampleDialog.java
public class SampleDialog extends CustomKeyboardDialog {
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sample_dialog);
}
#Nullable
#Override
public void onCreateView(View contentView) {
EditText editText = (EditText) findViewById(R.id.edittext);
attachToCustomKeyboard(editText);
}
}
sample_dialog.xm
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="50dp"
android:layout_marginLeft="50dp"
android:background="#eee">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="32dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Enter Code"></TextView>
<EditText
android:id="#+id/edittext"
android:hint="example: *455*415#"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:text="Send"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</LinearLayout>
and it looks like this:

Two checkbox in recyclerview changing state when scrolling

Edit
Solved issue by removing two lines
holder.checkbox.setChecked(mListenerList.get(position).isSelected());
holder.checkbox.setChecked(mListenerList.get(position).isSelected2());
And By Adding
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
I am not editing my original code for future developers.
Main Question before Edit Start from Here
I am working on fantasy cricket app where I am selecting the captain and vice captain from a list of 11 player.
I am using a checkbox for selecting the captain and vice captain.
The selection of checkbox is working fine with my code, but the issue is when I select 1st player as a captain(C) and 2nd player as Vice-Captain(VC) and then scroll the list the checkbox state is changing and showing other player selected.
So is there any right way to do that thing?
I have tried many way they are working when there is single checkbox but in my case there is two and only one can be select from the list.
Please refer to the attached screenshots on the bottom for clarity.
Adapter Class
public class AdapterFinalTeamList extends RecyclerView.Adapter<AdapterFinalTeamList.MyViewHolder> {
private List<BeanDBTeam> mListenerList;
Context mContext;
private CheckBox lastChecked = null;
private int lastCheckedPos = 0;
private CheckBox lastChecked2 = null;
private int lastCheckedPos2 = 0;
private RadioButton lastCheckedRB = null;
private RadioButton lastCheckedRB1 = null;
TextView PreviousCaptain = null;
TextView PreviousVC = null;
public AdapterFinalTeamList(List<BeanDBTeam> mListenerList, Context context) {
mContext = context;
this.mListenerList = mListenerList;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView tv_PlayerName,tv_SelectCaptain,tv_SelectViceCaptain, tv_PlayerTeamName, tv_PlayerPoints,tv_TeamNumber;
ImageView im_PlayerImage,im_onetwox;
CheckBox checkbox,checkbox2;
RadioGroup radiogroup;
RadioButton radio,radio2;
public MyViewHolder(View view) {
super(view);
tv_PlayerName =view.findViewById(R.id.tv_PlayerName);
tv_PlayerTeamName = view.findViewById(R.id.tv_PlayerTeamName);
tv_PlayerPoints = view.findViewById(R.id.tv_PlayerPoints);
im_PlayerImage = view.findViewById(R.id.im_PlayerImage);
im_onetwox = view.findViewById(R.id.im_onetwox);
tv_TeamNumber = view.findViewById(R.id.tv_TeamNumber);
tv_SelectViceCaptain = view.findViewById(R.id.tv_SelectViceCaptain);
tv_SelectCaptain= view.findViewById(R.id.tv_SelectCaptain);
checkbox= view.findViewById(R.id.checkbox);
checkbox2= view.findViewById(R.id.checkbox2);
radiogroup= view.findViewById(R.id.radiogroup);
radio= view.findViewById(R.id.radio);
radio2= view.findViewById(R.id.radio2);
}
}
#Override
public int getItemCount() {
return mListenerList.size();
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.adapter_final_list, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
String id = mListenerList.get(position).getMatchId();
String arrayList = (mListenerList.get(position).getPlayerData());
try {
JSONObject job = new JSONObject(arrayList);
String PlayerName = job.getString("name");
String PlayerImage = job.getString("image");
String PlayerPoints = job.getString("player_points");
String PlayerCredit = job.getString("credit_points");
String TeamShortName = job.getString("team_short_name");
String team_number = job.getString("team_number");
String player_shortname = job.getString("player_shortname");
holder.tv_TeamNumber.setText(team_number);
// PlayerTeam= job.getString("short_name");
holder.tv_PlayerName.setText(PlayerName);
holder.tv_PlayerPoints.setText(PlayerPoints);
holder.tv_PlayerTeamName.setText(TeamShortName);
Glide.with(activity).load(Config.PLAYERIMAGE + PlayerImage)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(holder.im_PlayerImage);
} catch (JSONException e) {
e.printStackTrace();
}
holder.checkbox.setChecked(mListenerList.get(position).isSelected());
holder.checkbox.setTag(new Integer(position));
holder.checkbox.setChecked(mListenerList.get(position).isSelected2());
holder.checkbox2.setTag(new Integer(position));
holder.checkbox.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
int clickedPos = ((Integer) cb.getTag()).intValue();
holder.checkbox2.setChecked(false);
if (cb.isChecked()) {
if (lastChecked != null) {
mListenerList.get(lastCheckedPos).setSelected(false);
lastChecked.setChecked(false);
}
else if (clickedPos==position){
lastCheckedPos = clickedPos;
lastChecked = cb;
lastChecked.setChecked(true);
}
lastCheckedPos = clickedPos;
lastChecked = cb;
} else
lastChecked = null;
try {
lastChecked.setChecked(true);
}
catch (Exception e){
e.printStackTrace();
}
mListenerList.get(clickedPos).setSelected(cb.isChecked());
CaptainId = mListenerList.get(position).getPlayerId();
}
});
holder.checkbox2.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
int clickedPos = ((Integer) cb.getTag()).intValue();
holder.checkbox.setChecked(false);
if (cb.isChecked()) {
if (lastChecked2 != null) {
lastChecked2.setChecked(false);
mListenerList.get(lastCheckedPos2).setSelected(false);
}
else if (clickedPos==position){
lastChecked2 = cb;
lastCheckedPos2 = clickedPos;
lastChecked2.setChecked(true);
}
lastChecked2 = cb;
lastCheckedPos2 = clickedPos;
} else
lastChecked2 = null;
try{
lastChecked2.setChecked(true);
}
catch (Exception e){
e.printStackTrace();
}
mListenerList.get(clickedPos).setSelected2(cb.isChecked());
ViceCaptainId = mListenerList.get(position).getPlayerId();
}
});
}
}
adapter_final_list.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res /android"
android:layout_width="match_parent"
android:background="#color/white"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="2dp"
android:padding="5dp"
android:id="#+id/RL_PlayerListMain"
android:elevation="0dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tv_TeamNumber"
android:visibility="invisible"/>
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#drawable/logo"
android:layout_centerVertical="true"
android:id="#+id/im_PlayerImage"/>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:id="#+id/RL_Name"
android:layout_toRightOf="#+id/im_PlayerImage"
android:layout_marginLeft="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Player Name"
android:id="#+id/tv_PlayerName"
android:textColor="#1e1e1e"
/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center"
android:layout_below="#+id/tv_PlayerName">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="IND"
android:layout_gravity="center"
android:layout_marginRight="5dp"
android:id="#+id/tv_PlayerTeamName"
android:textColor="#1e1e1e"
/>
<View
android:layout_width="1dp"
android:layout_height="10dp"
android:layout_gravity="center"
android:background="#8e8e8e"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="55 Points"
android:layout_gravity="center"
android:id="#+id/tv_PlayerPoints"
android:textColor="#8e8e8e"
android:layout_marginLeft="5dp"
/>
</LinearLayout>
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:id="#+id/RL_Credit"
android:layout_alignParentRight="true">
<TextView
android:layout_width="40dp"
android:layout_height="40dp"
android:text="C"
android:padding="10dp"
android:textAlignment="center"
android:gravity="center"
android:visibility="gone"
android:layout_centerVertical="true"
android:background="#drawable/circle_captain_vc_back"
android:id="#+id/tv_SelectCaptain"
android:textColor="#1e1e1e"
android:layout_marginLeft="10dp"
/>
<CheckBox
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_toRightOf="#+id/tv_SelectViceCaptain"
android:layout_centerVertical="true"
android:visibility="visible"
android:text="C"
android:textColor="#1e1e1e"
android:gravity="center"
android:button="#android:color/transparent"
android:background="#drawable/radio_selector"
android:id="#+id/checkbox"/>
<CheckBox
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_toRightOf="#+id/checkbox"
android:layout_centerVertical="true"
android:visibility="visible"
android:text="VC"
android:layout_marginLeft="5dp"
android:textColor="#1e1e1e"
android:gravity="center"
android:button="#android:color/transparent"
android:background="#drawable/radio_vc_selector"
android:id="#+id/checkbox2"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/onex_icon"
android:visibility="invisible"
android:layout_centerHorizontal="true"
android:id="#+id/im_onetwox"
/>
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/radiogroup"
android:visibility="gone"
android:layout_marginTop="10dp"
android:layout_below="#+id/im_onetwox"
android:orientation="horizontal">
<RadioButton
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_toRightOf="#+id/tv_SelectViceCaptain"
android:layout_centerVertical="true"
android:visibility="visible"
android:text="C"
android:layout_marginRight="10dp"
android:gravity="center"
android:background="#drawable/radio_selector"
android:button="#android:color/transparent"
android:id="#+id/radio"/>
<RadioButton
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_toRightOf="#+id/checkbox"
android:layout_centerVertical="true"
android:visibility="visible"
android:text="VC"
android:gravity="center"
android:background="#drawable/radio_vc_selector"
android:button="#android:color/transparent"
android:id="#+id/radio2"/>
</RadioGroup>
<TextView
android:layout_width="40dp"
android:layout_height="40dp"
android:text="VC"
android:textAlignment="center"
android:gravity="center"
android:visibility="gone"
android:padding="10dp"
android:layout_toRightOf="#+id/tv_SelectCaptain"
android:layout_centerVertical="true" android:background="#drawable/circle_captain_vc_back"
android:id="#+id/tv_SelectViceCaptain"
android:textColor="#1e1e1e"
android:layout_marginLeft="10dp"
/>
</RelativeLayout>
</RelativeLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#8e8e8e"
android:layout_marginTop="5dp"
android:layout_marginBottom="2dp"
android:layout_marginRight="5dp"
android:layout_marginLeft="5dp"
android:layout_below="#+id/RL_PlayerListMain"/>
</RelativeLayout>
Selecting C and VC
After scrolling top to bottom and bottom to top
Please ignore Radio group. My code is working fine with checkbox, it's only creating issues when scrolling.
For checkbox you need to use checkbox.OnCheckedChangeListener() instead of checkbox.setOnClickListener()
Follow this steps
add a new Boolean variable in your BeanDBTeam class
public class BeanDBTeam
{
boolean isChecked;
public boolean getisChecked() {
return isChecked;
}
public void setIsChecked(boolean flag) {
isChecked= flag;
}
}
Now inside you onBindViewHolder() add below code
#Override
public void onBindViewHolder(#NonNull ViewHolder viewHolder, int position) {
BeanDBTeam bean = mListenerList.get(position).getisChecked()
// check here the flag and status of checkbox based on flag
holder.checkbox2.setChecked(bean.getisChecked());
holder.checkbox2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
// set flag of checkbox status in your list when user check or uncheck the checkbox
bean.setIsChecked(isChecked);
notifyDataChanged();
}
});
}
This is what recycling behaviour is, You can use other answer that are also correct but as you are having limited entries in your list you can actually disable recycling your recyclerview. Use below code in your adapter:
#Override
public void onBindViewHolder(final CommentViewHolder viewHolder, final int position) {
viewHolder.setIsRecyclable(false);
}
As #Nilesh suggested you , to use the Bean class for checkbox state remember functionality like below:
/**
* CheckType ==>>1 For the first checkbox
* CheckType ==>>2 For the second checkbox
* CheckType ==>>0 For the None
*/
public class BeanDBTeam
{
int checkType;
public int getCheckType() {
return checkType;
}
public void setCheckType(int checkType) {
this.checkType = checkType;
}
}
Inside the MyViewHolder you need to apply the setOnCheckedChangeListener listener and get position from the getAdapterPosition() like below
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView tv_PlayerName, tv_SelectCaptain, tv_SelectViceCaptain, tv_PlayerTeamName, tv_PlayerPoints, tv_TeamNumber;
ImageView im_PlayerImage, im_onetwox;
CheckBox checkbox, checkbox2;
RadioGroup radiogroup;
RadioButton radio, radio2;
public MyViewHolder(View view) {
super(view);
tv_PlayerName = view.findViewById(R.id.tv_PlayerName);
tv_PlayerTeamName = view.findViewById(R.id.tv_PlayerTeamName);
tv_PlayerPoints = view.findViewById(R.id.tv_PlayerPoints);
im_PlayerImage = view.findViewById(R.id.im_PlayerImage);
im_onetwox = view.findViewById(R.id.im_onetwox);
tv_TeamNumber = view.findViewById(R.id.tv_TeamNumber);
tv_SelectViceCaptain = view.findViewById(R.id.tv_SelectViceCaptain);
tv_SelectCaptain = view.findViewById(R.id.tv_SelectCaptain);
checkbox = view.findViewById(R.id.checkbox);
checkbox2 = view.findViewById(R.id.checkbox2);
radiogroup = view.findViewById(R.id.radiogroup);
radio = view.findViewById(R.id.radio);
radio2 = view.findViewById(R.id.radio2);
/**
* NOW WE APPLY THE setOnCheckedChangeListener functionality for the checkboxlistener
*/
checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// set flag of checkbox status in your list when user check or uncheck the checkbox
if (checkbox) {
YOUR_ARRAYLIST.get(getAdapterPosition()).setCheckType(1);
}
else {
YOUR_ARRAYLIST.get(getAdapterPosition()).setCheckType(0);
}
notifyDataChanged();
}
});
checkbox2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// set flag of checkbox status in your list when user check or uncheck the checkbox
if (checkbox) {
YOUR_ARRAYLIST.get(getAdapterPosition()).setCheckType(2);
}
else {
YOUR_ARRAYLIST.get(getAdapterPosition()).setCheckType(0);
}
notifyDataChanged();
}
});
}
}
And inside the onBindViewHolder we need to set the Checkbox according to the selection like below
#Override
public void onBindViewHolder(#NonNull ViewHolder viewHolder, int position) {
BeanDBTeam bean = mListenerList.get(position).getisChecked()
// check here the flag and status of checkbox based on flag
if(bean.getCheckType()==0) {
holder.checkbox.setChecked(false);
holder.checkbox2.setChecked(false);
}
else if(bean.getCheckType()==1) {
holder.checkbox.setChecked(true);
holder.checkbox2.setChecked(false);
}
else if(bean.getCheckType()==2) {
holder.checkbox.setChecked(false);
holder.checkbox2.setChecked(true);
}
}

RadioButton state and Button validation

I am facing two issues.
Radio buttons in radiogroup loosing state: when I click yes or no and scroll down the list view it looses the radiobutton value which is checked. I tried many ways to fix it but unable to achieve.
Submit button validation(Please refer image four): list of questions user should select either yes or no before clicking on submit button, if user click on submit button without selecting either yes or no it should them a toast message. all the questions should be selected with either yes or no. More specific each radiogroup should give me yes or no, not empty string.
Thanks in advance.
Custom Adapter
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;
selectedAnswers = new ArrayList<>();
for (int i = 0; i < questionsList.length; i++) {
selectedAnswers.add("");
}
inflter = (LayoutInflater.from(applicationContext));
}
#Override
public int getCount() {
return questionsList.length;
}
#Override
public Object getItem(int i) {
return i;
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public int getViewTypeCount() {
return questionsList.length;
}
#Override
public int getItemViewType(int i) {
return i;
}
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
view = inflter.inflate(R.layout.list_items, null);
TextView question = (TextView) view.findViewById(R.id.question);
final RadioButton yes = (RadioButton) view.findViewById(R.id.yes);
final RadioButton no = (RadioButton) view.findViewById(R.id.no);
final RadioGroup rg = (RadioGroup) view.findViewById(R.id.radio_group);
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (yes.isChecked()) {
yes.setBackgroundColor(Color.GREEN);
no.setBackgroundColor(Color.BLACK);
}
if (no.isChecked()){
no.setBackgroundColor(Color.rgb(255,165,0));
yes.setBackgroundColor(Color.BLACK);
}
}
});
yes.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked)
selectedAnswers.set(i, "1");
}
});
no.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked)
selectedAnswers.set(i, "2");
}
});
question.setText(questionsList[i]);
return view;
}
Main Activity
public class MainActivity extends AppCompatActivity {
ListView simpleList;
String[] questions;
Button submit,submit1;
FileOutputStream fstream;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
questions = getResources().getStringArray(R.array.questions);
simpleList = (ListView) findViewById(R.id.simpleListView);
View footerView = getLayoutInflater().inflate(R.layout.footer,null);
submit = (Button) footerView.findViewById(R.id.submit1);
simpleList.addFooterView(footerView);
View headerView = getLayoutInflater().inflate(R.layout.header, null);
simpleList.addHeaderView(headerView);
CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), questions);
simpleList.setAdapter(customAdapter);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String message = "";
for (int i = 0; i < CustomAdapter.selectedAnswers.size(); i++) {
message = message + "\n" + (i + 1) + " " + CustomAdapter.selectedAnswers.get(i);
}
try {
fstream = openFileOutput("user_answer", Context.MODE_PRIVATE);
fstream.write(message.getBytes());
fstream.close();
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
Intent inent = new Intent(v.getContext(), DetailsActivity.class);
startActivity(inent);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
XML main layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/Black"
android:padding="10dp">
<RelativeLayout
android:id="#+id/main"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:background="#drawable/round_relativelayout"
>
<ListView
android:id="#+id/simpleListView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#color/Black"
android:dividerHeight="1dp"
android:footerDividersEnabled="false"
/>
</RelativeLayout>
List item XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:background="#color/LightGrey">
<!-- TextView for displaying question-->
<TextView
android:id="#+id/question"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:padding="#dimen/activity_horizontal_margin"
android:textColor="#000"
android:textSize="30dp"
android:text="Which is your most favorite?"
/>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:id="#+id/main">
<RadioGroup
android:id="#+id/radio_group"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="horizontal">
<RadioButton
android:id="#+id/yes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="20dp"
android:background="#color/Black"
android:button="#null"
android:paddingHorizontal="30dp"
android:paddingVertical="5dp"
android:text="YES"
android:textColor="#color/White"
android:textSize="50dp" />
<RadioButton
android:id="#+id/no"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:background="#color/Black"
android:button="#null"
android:paddingHorizontal="30dp"
android:paddingVertical="5dp"
android:text="NO"
android:textColor="#color/White"
android:textSize="50dp" />
</RadioGroup>
</FrameLayout>
Image oneImage twoImage threeImage four with submit button
Try the following:
1) MainActivity_.class:-----
public class MainActivity_ extends AppCompatActivity {
private ListView lv;
private CustomAdapter customAdapter;
private String[] questions;
private Button submit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout8);
questions = new String[10];
for(int i = 0 ; i<10 ; i++){
questions[i] = "Q " + i;
}
lv = (ListView) findViewById(R.id.lv);
customAdapter = new CustomAdapter(getApplicationContext() , questions);
lv.setAdapter(customAdapter);
submit = (Button) findViewById(R.id.submit);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
boolean found_unanswered = false;
if(customAdapter != null){
for(int i = 0 ; i<customAdapter.getSelectedAnswers().size() ; i++){
if(customAdapter.getSelectedAnswers().get(i).equals("3")){
found_unanswered = true;
break;
}
}
}
if(!found_unanswered){
Toast.makeText(getApplicationContext() , "All Answered" , Toast.LENGTH_LONG).show();
//Go to other activity
}
}
});
}
}
2) CustomAdapter.class:------
public class CustomAdapter extends BaseAdapter {
Context context;
String[] questionsList;
LayoutInflater inflter;
public ArrayList<String> selectedAnswers;
public CustomAdapter(Context applicationContext, String[] questionsList) {
this.context = context;
this.questionsList = questionsList;
selectedAnswers = new ArrayList<>();
for (int i = 0; i < questionsList.length; i++) {
selectedAnswers.add("3");
}
inflter = (LayoutInflater.from(applicationContext));
}
#Override
public int getCount() {
return questionsList.length;
}
#Override
public Object getItem(int i) {
return questionsList[i];
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public int getViewTypeCount() {
return questionsList.length;
}
#Override
public int getItemViewType(int i) {
return i;
}
#Override
public View getView(final int i, View convertView, ViewGroup viewGroup) {
View view = convertView;
if (convertView == null) {
if (inflter != null) {
view = inflter.inflate(R.layout.list_items, null);
}
}
TextView question = (TextView) view.findViewById(R.id.question);
question.setText(questionsList[i]);
// initialize/ restore UI Radio Button State
final RadioGroup rg = (RadioGroup) view.findViewById(R.id.radio_group);
RadioButton rb_yes = (RadioButton) rg.findViewById(R.id.yes);
RadioButton rb_no = (RadioButton) rg.findViewById(R.id.no);
if(selectedAnswers.get(i).equals("1")){
rg.check(R.id.yes);
rb_yes.setBackgroundColor(Color.GREEN);
rb_no.setBackgroundColor(Color.GRAY);
}else if(selectedAnswers.get(i).equals("2")){
rg.check(R.id.no);
rb_yes.setBackgroundColor(Color.GRAY);
rb_no.setBackgroundColor(Color.BLACK);
}else{
// no answer.
rb_yes.setBackgroundColor(Color.GRAY);
rb_no.setBackgroundColor(Color.GRAY);
}
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton rb_yes = (RadioButton) group.findViewById(R.id.yes);
RadioButton rb_no = (RadioButton) group.findViewById(R.id.no);
switch (checkedId){
case R.id.yes:
rb_yes.setBackgroundColor(Color.GREEN);
rb_no.setBackgroundColor(Color.GRAY);
selectedAnswers.set(i, "1");
break;
case R.id.no:
rb_yes.setBackgroundColor(Color.GRAY);
rb_no.setBackgroundColor(Color.BLACK);
selectedAnswers.set(i, "2");
break;
}
}
});
return view;
}
public List<String> getSelectedAnswers(){
return selectedAnswers;
}
}
3) layout8.xml:------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="100">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="80"
android:id="#+id/lv">
</ListView>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/lv"
android:layout_weight="20"
android:text="Submit"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:id="#+id/submit"/>
</LinearLayout>
4) list_items.xml:-----
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical">
<!-- TextView for displaying question-->
<TextView
android:id="#+id/question"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textColor="#000"
android:textSize="30dp"
android:text="Which is your most favorite?"
/>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:id="#+id/main">
<RadioGroup
android:id="#+id/radio_group"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="horizontal">
<RadioButton
android:id="#+id/yes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="20dp"
android:button="#null"
android:paddingHorizontal="30dp"
android:paddingVertical="5dp"
android:text="YES"
android:textSize="50dp" />
<RadioButton
android:id="#+id/no"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:button="#null"
android:paddingHorizontal="30dp"
android:paddingVertical="5dp"
android:text="NO"
android:textSize="50dp" />
</RadioGroup>
</FrameLayout>
</LinearLayout>
Try this.
Use ViewHolder so it does not lose the data set
Custom Adapter class
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
ViewHolder viewHolder;
if(view == null){
view = inflter.inflate(R.layout.list_items, null);
viewHolder = new ViewHolder();
ViewHoldwe.question = (TextView) view.findViewById(R.id.question);
viewHolder.yes = (RadioButton) view.findViewById(R.id.yes);
viewHolder.no = (RadioButton) view.findViewById(R.id.no);
viewHolder.rg = (RadioGroup) view.findViewById(R.id.radio_group);
view.setTag(viewHolder)
}else{
viewHolder = (ViewHolder) view.getTag();
viewHolder.rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (viewHolder.yes.isChecked()) {
viewHolder.yes.setBackgroundColor(Color.GREEN);
viewHolder.no.setBackgroundColor(Color.BLACK);
}
if (viewHolder.no.isChecked()){
viewHolder.no.setBackgroundColor(Color.rgb(255,165,0));
viewHolder.yes.setBackgroundColor(Color.BLACK);
}
}
});
viewHolder.yes.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked)
selectedAnswers.set(i, "1");
}
});
viewHolder.no.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked)
selectedAnswers.set(i, "2");
}
});
question.setText(questionsList[i]);
}
return view;
}
Make a private inner class
private class ViewHolder{
RadioButton yes;
TextView question;
RadioButton no ;
RadioGroup rg;
}

RadioGroup listener dont work

I have a Fragment that displays a Dialog.
Inside that Dialog there is a RadioGroup.
I tried to create a listener to this RadioGroup, but i didn't successed.
Fragment --> Dialog --> RadioGroup
I tried four ways:
OnCheckedChangeListener on RadioGroup.
OnClickListener on RadioGroup.
OnCheckedChangeListener on RadioButton.
OnClickListener on RadioButton
No one worked.
Here is my code:
The Dialog - layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioGroup
android:id="#+id/bS_rg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:orientation="vertical">
<RadioButton
android:id="#+id/r_id"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="ID"
android:textSize="24sp" />
<RadioButton
android:id="#+id/r_title"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="Title"
android:textSize="24sp" />
<RadioButton
android:id="#+id/r_genre"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="Genre"
android:textSize="24sp" />
<RadioButton
android:id="#+id/r_author"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="Author"
android:textSize="24sp" />
</RadioGroup>
<AutoCompleteTextView
android:id="#+id/c_bSearch"
android:layout_width="278dp"
android:layout_height="72dp"
android:singleLine="true"/>
</LinearLayout>
The Fragment - layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<de.codecrafters.tableview.TableView
android:id="#+id/tableView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
And the Fragment - code: (I marked where is the problem, the other code is not important)
package com.example.adiel.library_app_30;
import .....;
public class ShowAllBooks extends Fragment {
View v;
TableLayout table;
TableRow row;
String[] spaceProbeHeaders = {"ID", "Title"};
String[][] spaceProbes;
AutoCompleteTextView c_search;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
v = inflater.inflate(R.layout.show_all_books, container, false);
setHasOptionsMenu(true);
/*
------The problem is here----
*/
LayoutInflater li = LayoutInflater.from(v.getContext());
View promptsView = li.inflate(R.layout.b_search_dialog, null);
c_search = (AutoCompleteTextView) promptsView.findViewById(R.id.c_bSearch);
RadioGroup rg = (RadioGroup) promptsView.findViewById(R.id.bS_rg);
rg.check(R.id.r_id);
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId)
{
Log.d("Log", "Clicked");
}
});
rg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Log", "Clicked");
}
});
RadioButton r_id = (RadioButton) promptsView.findViewById(R.id.r_id);
r_id.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.d("Log", "Clicked");
}
});
r_id.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Log", "Clicked");
}
});
/*
------Until here----
*/
final TableView<String[]> tb = (TableView<String[]>) v.findViewById(R.id.tableView);
tb.setColumnCount(2);
tb.setHeaderBackgroundColor(Color.parseColor("#2ecc71"));
Ask a = new Ask("books", "getAllCopiesOfBooks", null);
Client client = (Client) new Client(a, a.getIp(), v.getContext(), new Client.ClientReply() {
#Override
public void processFinish(Object output) {
if (output != null) {
ArrayList<CopyId> data = (ArrayList<CopyId>) output;
spaceProbes = new String[data.size()][2];
for (int i = 0; i < data.size(); i++) {
CopyId c = data.get(i);
spaceProbes[i][0] = String.valueOf(c.getId());
spaceProbes[i][1] = c.getTitle();
}
tb.setHeaderAdapter(new SimpleTableHeaderAdapter(v.getContext(), spaceProbeHeaders));
tb.setDataAdapter(new SimpleTableDataAdapter(v.getContext(), spaceProbes));
}
}
}).execute();
tb.addDataClickListener(new TableDataClickListener() {
#Override
public void onDataClicked(int rowIndex, Object clickedData) {
Toast.makeText(v.getContext(), ((String[]) clickedData)[0], Toast.LENGTH_SHORT).show();
Intent i = new Intent(v.getContext(), ShowBook.class);
i.putExtra("id", ((String[]) clickedData)[0]);
startActivity(i);
}
});
return v;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.showallbooks_menu, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.action_add:
return true;
case R.id.action_search:
search_func();
return true;
}
return super.onOptionsItemSelected(item);
}
public void search_func(){
final Dialog dialog = new Dialog(v.getContext());
dialog.setContentView(R.layout.b_search_dialog);
dialog.setTitle("Search");
dialog.show();
//RadioButton r_id = (RadioButton) promptsView.findViewById(R.id.r_id);
/*RadioButton r_title = (RadioButton) v.findViewById(R.id.r_title);
RadioButton r_genre = (RadioButton) v.findViewById(R.id.r_genre);
RadioButton r_author = (RadioButton) v.findViewById(R.id.r_author);*/
}
}

How to get value of all selected radio buttons from all the views in sliding Fragment

I have three views in sliding Fragment with Survey Questions having dynamic radiobuttons (the layout for all views are same, i am just repeating). I can get the data of selected radiobuttons from one screen, but how can i get the data of all selected radiobuttons from all screens ? Below is my working code
FragmentActivity.java
public class MainActivity extends FragmentActivity {
static final int ITEMS = 3;
MyAdapter mAdapter;
ViewPager mPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_pager);
mAdapter = new MyAdapter(getSupportFragmentManager());
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
Button button = (Button) findViewById(R.id.first);
Button submitaldatabutton = (Button) findViewById(R.id.first);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mPager.setCurrentItem(0);
}
});
button = (Button) findViewById(R.id.last);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mPager.setCurrentItem(ITEMS - 1);
}
});
submitaldatabutton = (Button) findViewById(R.id.submitalldata);
submitaldatabutton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//Get all data
}
});
}
public static class MyAdapter extends FragmentStatePagerAdapter {
public MyAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
#Override
public int getCount() {
return ITEMS;
}
#Override
public Fragment getItem(int position) {
// TODO Auto-generated method stub
switch (position) {
case 0: // Fragment # 0 - This will show image
return LayoutFragment.init(position);
case 1: // Fragment # 1 - This will show image
return LayoutFragment.init(position);
default:// Fragment # 2-9 - Will show list
return LayoutFragment.init(position);
}
}
//#Override
/*public Fragment getItem(int position) {
switch (position) {
case 0: // Fragment # 0 - This will show image
return ImageFragment.init(position);
case 1: // Fragment # 1 - This will show image
return ImageFragment.init(position);
default:// Fragment # 2-9 - Will show list
return ArrayListFragment.init(position);
}
}*/
}
}
LayoutFragment.java
public class LayoutFragment extends Fragment {
int fragVal;
private String[] application = { "Country1", "Country2", "Country3", "Country4", "Country5", "Country6", "Country7", "Country8" };
private String[] device = { "Country9", "Country10", "Country11", "Country12", "Country13", "Country14", "Country15", "Country16" };
private RadioGroup radioGroup1;
private RadioGroup radioGroup2;
private RadioButton btn;
private RadioButton btn2;
private String text1;
private String text2;
RadioButton button1;
RadioButton button2;
Button selectall;
Context thiscontext;
static LayoutFragment init(int val) {
LayoutFragment truitonFrag = new LayoutFragment();
// Supply val input as an argument.
Bundle args = new Bundle();
args.putInt("val", val);
truitonFrag.setArguments(args);
return truitonFrag;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fragVal = getArguments() != null ? getArguments().getInt("val") : 1;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
thiscontext = container.getContext();
View layoutView = inflater.inflate(R.layout.activity_main, container, false);
Button myButton = (Button) layoutView.findViewById(R.id.findSelected);
myButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
StringBuffer responseText = new StringBuffer();
responseText.append("");
// Get selected radiobuttons
if (radioGroup1.getCheckedRadioButtonId() != -1) {
text1 = btn.getText().toString();
Log.d("Button", "Text 1 : " + text1);
}
if (radioGroup2.getCheckedRadioButtonId() != -1) {
text2 = btn2.getText().toString();
Log.d("Button", "Text 2 : " + text2);
}
Toast.makeText(
thiscontext,
"Data Posting : APPLICATION : "
+ text1 + " \nDEVICE : " + text2,
Toast.LENGTH_LONG).show();
}
});
//Draw Radiobuttons
radioGroup1 = (RadioGroup) layoutView.findViewById(R.id.radio1);
radioGroup2 = (RadioGroup) layoutView.findViewById(R.id.radio2);
ViewGroup hourButtonLayout = (ViewGroup) layoutView.findViewById(R.id.radio1);
for (int i = 0; i < application.length; i++) {
button1 = new RadioButton(thiscontext);
button1.setId(i);
button1.setText(application[i]);
hourButtonLayout.addView(button1);
radioGroup1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup mRadioGroup2,
int checkedId2) {
for (int i = 0; i < mRadioGroup2.getChildCount(); i++) {
btn = (RadioButton) mRadioGroup2.getChildAt(i);
int t = mRadioGroup2.getId();
System.out.println(t);
if (btn.getId() == checkedId2) {
text1 = btn.getText().toString();
Toast.makeText(thiscontext,
"You selected : " + text1,
Toast.LENGTH_SHORT).show();
return;
}
}
}
});
}
ViewGroup hourButtonLayout2 = (ViewGroup) layoutView.findViewById(R.id.radio2);
for (int i = 0; i < device.length; i++) {
button2 = new RadioButton(thiscontext);
button2.setId(i);
button2.setText(device[i]);
hourButtonLayout2.addView(button2);
radioGroup2
.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup mRadioGroup,
int checkedId) {
for (int i = 0; i < mRadioGroup.getChildCount(); i++) {
btn2 = (RadioButton) mRadioGroup.getChildAt(i);
int t = mRadioGroup.getId();
System.out.println(t);
if (btn2.getId() == checkedId) {
text2 = btn2.getText().toString();
Toast.makeText(thiscontext,
"You selected : " + text2,
Toast.LENGTH_SHORT).show();
return;
}
}
}
});
}
return layoutView;
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#fff">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:textColor="#000"
android:text="Select Question1"
android:textSize="18sp"/>
<Button
android:id="#+id/findSelected"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Submit"/>
<ScrollView
android:layout_width="fill_parent"
android:layout_height="200dip"
android:orientation="vertical"
android:scrollbars="none" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="200dip"
android:orientation="vertical">
<RadioGroup
android:id="#+id/radio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dip"
android:layout_marginTop="5dip"
android:background="#fff"
android:checkedButton="#+id/sound" >
</RadioGroup>
</LinearLayout>
</ScrollView>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginTop="5dip"
android:layout_marginBottom="5dip"
android:text="Select Question2"
android:textColor="#000"
android:textSize="18sp"/>
<ScrollView
android:layout_width="fill_parent"
android:layout_height="360dip"
android:orientation="vertical"
android:scrollbars="none" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="560dip"
android:orientation="vertical">
<RadioGroup
android:id="#+id/radio2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dip"
android:layout_marginTop="5dip"
android:background="#fff"
android:checkedButton="#+id/sound">
</RadioGroup>
</LinearLayout>
</ScrollView>
</LinearLayout>
fragment_pager.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
android:padding="4dip" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1" >
</android.support.v4.view.ViewPager>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0"
android:gravity="center"
android:measureWithLargestChild="true"
android:orientation="horizontal" >
<Button
android:id="#+id/first"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="First" >
</Button>
<Button
android:id="#+id/last"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Last" >
</Button>
<Button
android:id="#+id/submitalldata"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit AllData" >
</Button>
</LinearLayout>
</LinearLayout>

Categories

Resources