I have a custom AlertDialog with radio buttons which will open on click of a textview. Everything is working as it is supposed to except that the radio buttons are never shown as "checked". Whenever I open the AlertDialog all of the buttons are unchecked. After selecting a button and opening the AlertDialog again the buttons are unchecked again.
My XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="15dp">
<RadioGroup
android:id="#+id/rg_gender"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_marginRight="30dp"
android:layout_marginLeft="30dp"
android:layout_marginTop="10dp"
android:orientation="vertical"
android:layout_gravity="center_horizontal">
<RadioButton
android:id="#+id/buttonMale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/therapist_male"
/>
<RadioButton
android:id="#+id/buttonFemale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/therapist_female"
/>
<RadioButton
android:id="#+id/buttonEither"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/therapist_either"
/>
</RadioGroup>
</LinearLayout>
My AlertDialog:
private void therapistDialog() {
final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View dialogView = inflater.inflate(R.layout.gender_dialog, null);
dialogBuilder.setView(dialogView);
dialogBuilder.setNegativeButton(getResources().getString(R.string.cancel_button), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
final AlertDialog alertDialog = dialogBuilder.show();
final RadioGroup rg = (RadioGroup) dialogView.findViewById(R.id.rg_gender);
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId == R.id.buttonMale){
tvGender.setText(getResources().getString(R.string.therapist_male));
therapistSex = 0;
mMassage.setTherapistSex(therapistSex);
male.setChecked(true);
alertDialog.dismiss();
} else if (checkedId == R.id.buttonFemale){
tvGender.setText(getResources().getString(R.string.therapist_female));
therapistSex = 1;
mMassage.setTherapistSex(therapistSex);
alertDialog.dismiss();
} else if (checkedId == R.id.buttonEither){
tvGender.setText(getResources().getString(R.string.therapist_either));
therapistSex = 2;
mMassage.setTherapistSex(therapistSex);
alertDialog.dismiss();
}
}
});
You are not restoring the state of dialog on opening and assign a new instance of AlertDialog every time You invoke therapistDialog method.
Try to check the button on AlertDialog view init.
Add
int buttonToCheck = mMassage.getTherapistSex();
RadioGroup radioGroup = dialogView.findViewById(R.id.rg_gender);
int buttonId = radioGroup.getChildAt(buttonToCheck).getId();
radioGroup.check(radioGroup.getChildAt(buttonToCheck).getId());
Before invoking dialogBuilder.setView(dialogView);
Every time you call the method therapistDialog() is creating a new instance of the alertDialogBuilder. You must create instance of the alertDialogBuilder only once globally,
and just call
final AlertDialog alertDialog = dialogBuilder.show(); inside your method.
note: this is not tested but this should work and will maintain your check box states also
Related
I have an alert dialog with a spinner in it. I like to change the text of the positive button depending on the spinner position.
mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
if (position == 0) {
/////
// I have access to the dialog object here and need to change the positive button text
////
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
Here's how i did it.
Declared buttons My Class
MaterialButton positiveBtn,negativeBtn;
Created my function and initialized my buttons
void alertDialog(){
AlertDialog.Builder dialogBuilder = new
AlertDialog.Builder(requireActivity());
LayoutInflater inflater = this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.test_layout, null);
dialogBuilder.setView(dialogView);
positiveBtn = dialogView.findViewById(R.id.btn_positive);
negativeBtn = dialogView.findViewById(R.id.btn_negative);
AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();
negativeBtn.setOnClickListener(v -> {
positiveBtn.setText("Text 2 Positive ");
});
}
Here is the test_layout
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_margin="16dp"
android:layout_height="wrap_content">
<com.google.android.material.button.MaterialButton
android:id="#+id/btn_positive"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Text 1 Positive "
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent">
</com.google.android.material.button.MaterialButton>
<com.google.android.material.button.MaterialButton
app:layout_constraintTop_toBottomOf="#id/btn_positive"
android:id="#+id/btn_negative"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Cancel "
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent">
</com.google.android.material.button.MaterialButton>
</androidx.constraintlayout.widget.ConstraintLayout>
In your scenario you already have the custom layout for Alert Dialog just declare variables , intialize and set Text inside the spinner index wise.
this answer was inspired from here
I have created a custom alertdialog with a radiogroup, radiobuttons, and edittext.
The goal is to trying to get the text value from the selected radiobutton and the edittext. At this point, I can only get the value entered in the edittext.
I have seen the following link and tried to adjust the code to adapt, but it seems that the code still doesn't work.
Android getting value from selected radiobutton
http://www.mkyong.com/android/android-radio-buttons-example/
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<RadioGroup
android:id="#+id/radioPersonGroup"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<RadioButton
android:id="#+id/gButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginLeft="16dp"
android:layout_weight="1"
android:text="G" />
<RadioButton
android:id="#+id/kButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginLeft="16dp"
android:layout_weight="1"
android:text="K" />
</RadioGroup>
<EditText
android:id="#+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginLeft="16dp"
android:layout_weight="1"
android:ems="10"
android:hint="$10.00"
android:inputType="numberDecimal" />
</LinearLayout>
java file
private RadioButton radioSelectedButton;
...
FloatingActionButton fab = findViewById(R.id.fab);
final RadioGroup group = findViewById(R.id.radioPersonGroup);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
final View dialogView = getLayoutInflater().inflate(R.layout.custom_dialog, null);
builder.setTitle("Who Paid")
.setView(dialogView)
.setCancelable(false)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
int selectedId = group.getCheckedRadioButtonId();
radioSelectedButton = (RadioButton) findViewById(selectedId);
Toast.makeText(MainActivity.this,
radioSelectedButton.getText(), Toast.LENGTH_SHORT).show();
EditText input = dialogView.findViewById(R.id.editText2);
Toast.makeText(MainActivity.this,input.getText().toString(), Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
When I click on either buttons followed by the Ok to submit the dialog the following exception occurs.
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.widget.RadioGroup.getCheckedRadioButtonId()' on a null object reference
You're getting a NullPointerException in this line
int selectedId = group.getCheckedRadioButtonId();
because you tried to "find" the RadioGroup in the wrong View when you wrote
final RadioGroup group = findViewById(R.id.radioPersonGroup);
The RadioGroup is part of the Dialog, so you need to look for it in the View tree of dialogView:
// inside onClick()
final View dialogView = getLayoutInflater().inflate(R.layout.custom_dialog, null);
final RadioGroup group = dialogView.findViewById(R.id.radioPersonGroup);
Similarly, you need to "find" selectedRadioButton in a ViewGroup which contains it. e.g.
radioSelectedButton = (RadioButton) dialogView.findViewById(selectedId);
or
radioSelectedButton = (RadioButton) group.findViewById(selectedId);
I am able to make the RadarChart work with some static data. Now i want to display a alert dialog when users click on the radarchart to ask the user to input some data and then use this input data to redraw the chart.
I have created a MyMarkerView class which extends MarkerView and in the refreshContent method add the code for the Alert Dialog view.
But the problem is that whenever uses click the AlerDialog, the refreshContent is again called and a new alert Dialog is created - and the user is not able to enter anything.
Below is the code in the refreshContent method
LayoutInflater li = LayoutInflater.from(mContext);
View promptsView = li.inflate(R.layout.month_target_analysis_dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mContext);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
final EditText userInput1 = (EditText) promptsView.findViewById(R.id.textView1Edit);
final EditText userInput2 = (EditText) promptsView.findViewById(R.id.textView2Edit);
// set dialog message
alertDialogBuilder.setCancelable(false);
alertDialogBuilder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// get user input and set it to result
// edit text
//result.setText(userInput.getText());
String input1 = userInput1.getText().toString();
String input2 = userInput1.getText().toString();
if (userInput1.getError() == null && userInput2.getError() == null) {
//Do something
} else {
}
}
});
alertDialogBuilder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
Below is the Xml layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout_root"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="10dp" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="#string/l_target"
android:textAppearance="#style/ItemMedium" />
<EditText
android:id="#+id/textView1Edit"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:paddingLeft="50dp"
android:clickable="false"
android:inputType="number"
>
<requestFocus />
</EditText>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="#string/g_target"
android:textAppearance="#style/ItemMedium" />
<EditText
android:id="#+id/textView2Edit"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:paddingLeft="50dp"
android:clickable="false"
android:inputType="number"
>
</EditText>
</LinearLayout>
Any ideas how to disable the calling of refreshContent ?
Or is there any other better way of handling this ?
Thanks
Praveen
I was not able to make it work using the MarkerView. Instead i defined a setOnChartGestureListener to catch all the possible action on the chart and then handled the necessary action when the action was caught.
Seems to be working.
mChart.setOnChartGestureListener(new OnChartGestureListener() {
#Override
public void onChartSingleTapped(MotionEvent me) {
// TODO Auto-generated method stub
Log.e(LOG_TAG, "single tap");
}
#Override
public void onChartDoubleTapped(MotionEvent me) {
// TODO Auto-generated method stub
Log.e(LOG_TAG, "double tap");
}
}
Thanks
I want to create a dialog box when a button is clicked inside the dialog box I need 2 radio buttons which are linked with mobile default music and other is external memory of the mobile. Anyone can help me out this here is my code as follows?
buttonSound = (Button) findViewById(R.id.btn_sound);
buttonSound.setOnClickListener (new OnClickListener(){
public void onClick(View v){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
getApplicationContext());
Log.d("TAG","button inside mobile");
alertDialogBuilder
//.setMessage("Click yes to exit!")
.setCancelable(false)
.setPositiveButton("Sound",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
AlarmActivity.this.finish();
}
});
// builder.setPositiveButton("Sound", );
alertDialogBuilder
//.setMessage("Click yes to exit!")
.setCancelable(false)
.setPositiveButton("SdCard",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
Log.d("TAG","button inside sdCard");
AlarmActivity.this.finish();
}
});
alertDialogBuilder.show();
And it is showing error as follows given below
android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
Use AlarmActivity.this or this intead of getApplicationContext().
Create in layout in res/layout
radio_dialog_layout.xml
<RadioButton
android:id="#+id/rd_!"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="A" />
<RadioButton
android:id="#+id/rd_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/rd_!"
android:text="B" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/rd_2"
android:layout_centerInParent="true"
android:text="OK" />
</RelativeLayout>
create dialog in activity by using this code:
Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.radio_dialog_layout);
dialog.setTitle("This is my custom dialog box");
dialog.setCancelable(true);
// there are a lot of settings, for dialog, check them all out!
// set up radiobutton
RadioButton rd1 = (RadioButton) dialog.findViewById(R.id.rd_);
RadioButton rd2 = (RadioButton) dialog.findViewById(R.id.rd_2);
// now that the dialog is set up, it's time to show it
dialog.show();
You can also refer this tutorials: How to add lists, Checkboxes and Radio buttons to an AlertDialog – Android
Try this..
Change this..
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
getApplicationContext());
to
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
AlarmActivity.this);
EDIT
radio_btn.xml
<?xml version="1.0" encoding="UTF-8"?>
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/status_group"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:orientation="vertical" >
<RadioButton
android:id="#+id/default_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Default music" />
<RadioButton
android:id="#+id/external_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="External card music" />
</RadioGroup>
JAVa
LayoutInflater inflater = getLayoutInflater();
View dialoglayout = inflater.inflate(R.layout.radio_btn, (ViewGroup) getCurrentFocus());
RadioButton default_btn = (RadioButton) dialoglayout.findViewById(R.id.default_btn);
RadioButton external_btn = (RadioButton) dialoglayout.findViewById(R.id.external_btn);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
AlarmActivity.this);
Log.d("TAG","button inside mobile");
alertDialogBuilder
//.setMessage("Click yes to exit!")
.setCancelable(false)
.setView(dialoglayout);
.setPositiveButton("OK",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
AlarmActivity.this.finish();
}
});
alertDialogBuilder.show();
Create one xml file,
<RadioButton
android:id="#+id/radiobutton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hi" />
<RadioButton
android:id="#+id/radiobutton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/radiobutton1"
android:text="Bye" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/radiobutton2"
android:layout_centerInParent="true"
android:text="Click" />
and create Dialog in activity,
Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.activity_main);
dialog.setTitle("My Dialog Box");
dialog.setCancelable(true);
// set up radiobutton inside dialog box
RadioButton rb1 = (RadioButton) dialog.findViewById(R.id.radiobutton1);
RadioButton rb2 = (RadioButton) dialog.findViewById(R.id.radiobutton2);
// Show the dialog
dialog.show();
I have a Custom AlertDialog.Builder but I couldn't reach the EditText.
This is my DEFAULT Class;
AlertDialog.Builder Builder = new AlertDialog.Builder(this);
LayoutInflater Inflater = this.getLayoutInflater();
View AddCategory = Inflater.inflate(R.layout.category_new, null);
final EditText etCategoryName = (EditText) AddCategory.findViewById(R.id.btnAddCategory);
Builder.setView(AddCategory)
.setTitle("Add Category")
.setPositiveButton("ADD", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Time Today = new Time(Time.getCurrentTimezone());
Today.setToNow();
//This code has error !...
String CategoryName = etCategoryName.getText().toString();
}
})
.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
Builder.show();
This
String CategoryName = etCategoryName.getText().toString();
This is my Costum AlertDialog 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="60dp" >
<TextView
android:id="#+id/tvAddCategoryName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="10dp"
android:layout_marginTop="15dp"
android:text="#string/AddCategoryName"
android:textColor="#color/White"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/etAddCategoryName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/tvAddCategoryName"
android:layout_alignBottom="#+id/tvAddCategoryName"
android:layout_toRightOf="#+id/tvAddCategoryName"
android:layout_marginLeft="20dp"
android:hint="#string/CategoryName"
android:ems="10" >
<requestFocus />
</EditText>
Please help me ...
try this.
final EditText etCategoryName = (EditText) AddCategory.findViewById(R.id.etAddCategoryName);
In Your xml file your editText id is etAddCategoryName and in your java file you initialize different name (btnAddCategory).
So please change btnAddCategory to etAddCategoryName .
The Problem is occurred because you are passing button id instead of edittext id
Please Write below line of code
final EditText etCategoryName = (EditText) AddCategory.findViewById(R.id.etAddCategoryName);
instead of
final EditText etCategoryName = (EditText) AddCategory.findViewById(R.id.btnAddCategory);
If Seems like you mistyped the EditText id, you put R.id.btnAddCategory and seems like it should be R.id.etAddCategoryName.