How to pre select radio button using AlertDialog? - java

can someone help me with this? I have an AlertDialog box and its working fine, but what I want is when the alertdialog pops up, it will automatically check one of the radio button.
For an example "10 minutes" is checked when the alertdialog box pops up.
How to do that?
Below is my working code.
final CharSequence[] deleteFilesBy = {"5 minutes","10 minutes", "15 minutes"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Delete Files by?")
.setSingleChoiceItems(deleteFilesBy,-1, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
if(deleteFilesBy[which]=="5 minutes")
{
// do something
}
else if (deleteFilesBy[which]=="10 minutes")
{
// do something
}
else if (deleteFilesBy[which]=="15 minutes")
{
// do something
}
dialog.dismiss();
}
}).setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
arg0.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
PLEASE HELP!
Thanks
RJUY

TestRadio.java:
package com.dave.kelley;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
public class TestRadioActivity extends Activity {
int timeSetting = 0;
RadioButton radio0;
RadioButton radio1;
RadioButton radio2;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(listener);
radio0 = (RadioButton) findViewById(R.id.radio0);
radio1 = (RadioButton) findViewById(R.id.radio1);
radio2 = (RadioButton) findViewById(R.id.radio2);
}
public OnClickListener listener = new OnClickListener() {
public void onClick(View v) {
if (timeSetting == 0) {
radio0.setChecked(true);
radio1.setChecked(false);radio2.setChecked(false);
}
if (timeSetting == 1) {
radio1.setChecked(true);
radio0.setChecked(false);radio2.setChecked(false);
}
if (timeSetting == 2) {
radio2.setChecked(true);
radio0.setChecked(false);radio1.setChecked(false);
}
timeSetting++;
if(timeSetting == 3 || timeSetting > 3) {
timeSetting = 0;
}
}
};
}
main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<RadioGroup
android:id="#+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RadioButton
android:id="#+id/radio0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="RadioButton" />
<RadioButton
android:id="#+id/radio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="RadioButton" />
<RadioButton
android:id="#+id/radio2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="RadioButton" />
</RadioGroup>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>

This should do it.
RadioGroup rg = (RadioGroup) findViewById(R.id.radioGroup1);
rg.check(R.id.radioButton1);

just set the checked item as what you want...
builder.setTitle("Delete Files by?")
.setSingleChoiceItems(deleteFilesBy, WHICH ITEM YOU WANT , new DialogInterface.OnClickListener()

You can do this in XML:
<RadioButton
android:id="#+id/radio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="#string/sA" />
<RadioButton
android:id="#+id/radio2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/A" />
<RadioButton
android:id="#+id/radio3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/D" />
<RadioButton
android:id="#+id/radio4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/sD" />
</RadioGroup>
The first radiobutton, radio1, has the attribute android:checked="true". That means that when it loads, that radio will be defaulted, the user can still change it of course.
EDIT:
A more programmatic approach:
int timeSetting = 1;//say 0 = 5; 1=10; 2=15 (set this elsewhere in your code based
//on how you have predetermined the time length
RadioButton radio0 = (RadioButton) findViewById(R.id.radio0);
RadioButton radio1 = (RadioButton) findViewById(R.id.radio1);
RadioButton radio2 = (RadioButton) findViewById(R.id.radio2);
if (timeSetting == 0) {
radio0.setChecked(true);
radio1.setChecked(false);radio2.setChecked(false);
}
if (timeSetting == 1) {
radio1.setChecked(true);
radio0.setChecked(false);radio2.setChecked(false);
}
if (timeSetting == 2) {
radio2.setChecked(true);
radio0.setChecked(false);radio1.setChecked(false);
}

Related

Android - Click Button Inside alertDialog

I wonder how to click a Button inside of AlertDialog in Android and this is my code
activity_float_info.xml
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button" />
MainActivity.java
QR_ = LayoutInflater.from(MainActivity.this).inflate(R.layout.activity_float_info, null);
MAIN_QR_SCAN = (LinearLayout) findViewById(R.id.MAIN_QR_SCAN);
MAIN_QR_SCAN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new AlertDialog.Builder(MainActivity.this)
.setCancelable(Boolean.TRUE)
.setNegativeButton(getString(R.string.CANCEL), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
})
.setView(R.layout.activity_float_info)
.show();
button = (Button)QR_.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
button.setText("TEst");
}
});
}
});
I have inflate the layout..
I think the main problem is on
button = (Button)QR_.findViewById(R.id.button);
try this create a layout for dialog box
<TextView android:id="#+id/dialogtitle"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textColor="#android:color/black"
android:text="Please enter the email address you used for the account"
/>
<EditText
android:id="#+id/emailedittext"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:ems="10"
android:padding="5dp"
android:cursorVisible="true"
android:singleLine="true"
android:background="#android:color/white"
android:textColor="#android:color/black"
android:hint="Enter Mail id"
android:textSize="20dp" >
<requestFocus />
</EditText>
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:weightSum="2"
android:orientation="horizontal">
<Button
android:id="#+id/cancelbtn"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="CANCEL"/>
<Button
android:id="#+id/okbtn"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="Ok"/>
</LinearLayout>
Then create a dialog box using this layout and handle button clicks
final Dialog dialog = new Dialog(MainActivity.this);
// Include dialog.xml file
dialog.setContentView(R.layout.forgotpassword);
// Set dialog title
dialog.setTitle("ALERT!!");
// set values for custom dialog components - text, image and button
Button okbtn = (Button) dialog.findViewById(R.id.okbtn);
Button cancelbtn = (Button) dialog.findViewById(R.id.cancelbtn);
final EditText emailedittext = (EditText) dialog.findViewById(R.id.emailedittext);
dialog.show();
dialog.getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
// if decline button is clicked, close the custom dialog
cancelbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Close dialog
dialog.dismiss();
}
});
okbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email=emailedittext.getText().toString();
//do something more here
}
});
Refer: https://coderzpassion.com/android-show-alertdialog/
Here is a hack to use AlertDialog:
public class CustomDialog extends AlertDialog {
protected CustomDialog(Context context) {
super(context);
}
}
And then in your Activity:
CustomDialog dialog = new CustomDialog(this);
View view = getLayoutInflater().inflate(R.layout.custom_dialog_layout,null);
dialog.setView(view);
Button button = (Button)view.findViewById(R.id.custom_button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(YourActivity.this,"Your message", Toast.LENGTH_LONG).show();
}
});
dialog.show();
And the layout of the dialog (which has nothing in it barring the Button):
<?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="match_parent">
<Button
android:id="#+id/custom_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="New Button" />
</RelativeLayout>
And you should be able to see a Toast when you click on the button. Hope this helps.
Dialog is like a popup window to show some options to users(options like accept/decline).
Using class android.app.Dialog to create dialog.
Using dialog.xml file to create custom dialog layout.
Example:
res/layout/dialog.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ImageView
android:id="#+id/imageDialog"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="6dp" />
<TextView
android:id="#+id/textDialog"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#FFF"
android:layout_toRightOf="#+id/imageDialog"/>
<Button
android:id="#+id/declineButton"
android:layout_width="100px"
android:layout_height="wrap_content"
android:text=" Submit "
android:layout_marginTop="5dp"
android:layout_marginRight="5dp"
android:layout_below="#+id/textDialog"
android:layout_toRightOf="#+id/imageDialog"
/>
</RelativeLayout>
Java Code
// Create custom dialog object
final Dialog dialog = new Dialog(CustomDialog.this);
// Include dialog.xml file
dialog.setContentView(R.layout.dialog);
// Set dialog title
dialog.setTitle("Custom Dialog");
// set values for custom dialog components - text, image and button
TextView text = (TextView) dialog.findViewById(R.id.textDialog);
text.setText("Custom dialog Android example.");
ImageView image = (ImageView) dialog.findViewById(R.id.imageDialog);
image.setImageResource(R.drawable.image0);
dialog.show();
Button declineButton = (Button) dialog.findViewById(R.id.declineButton);
// if decline button is clicked, close the custom dialog
declineButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Close dialog
dialog.dismiss();
}
});

How to Choose Radio Button Value using Java Android?

If i'm click OK how to choose pick a value one service in radio button but different value.
void OpenDialogService() {
closeLyt.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
cancelTxt.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
okTxt.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
dialog.dismiss();
Bundle b = activity.getIntent().getExtras();
if(b == null)
b = new Bundle();
b.putString("service_id", "1");
startActivity(new Intent(activity, Step1.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP).putExtras(b));
overridePendingTransition(R.anim.push_left_in,R.anim.push_left_out);
}
});
dialog.show();
}
In this line for primary service :
b.putString("service_id", "1")
How i make conditional if service other give value :
b.putString("service_id", "2")
This is code snippet how you can achieve this with the help of RadioGroups
Your dialog layout should look like this :-
<LinearLayout 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"
android:orientation="vertical"
tools:context="com.example.test.MainActivity" >
<TextView
android:id="#+id/headerTxt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:background="#ff669900"
android:gravity="center_horizontal"
android:padding="5dp"
android:text="Pick Service"
android:textColor="#FFF"
android:textSize="20sp" />
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_margin="10dp"
android:layout_marginTop="32dp" >
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/primaryTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:checked="true"
android:text="Primary Service"
android:textSize="18sp" />
<TextView
android:id="#+id/primaryContentTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/primaryTxt"
android:text=" -Dusting \n -Sweeping \n -Washing \n -Cleaning " />
<RadioGroup
android:id="#+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true" >
<RadioButton
android:id="#+id/service_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<RadioButton
android:id="#+id/service_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp" />
</RadioGroup>
<TextView
android:id="#+id/otherTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/primaryContentTxt"
android:layout_marginTop="10dp"
android:checked="true"
android:gravity="left"
android:text="Other Service(Soon)"
android:textSize="18sp" />
</RelativeLayout>
</RelativeLayout>
<LinearLayout
android:id="#+id/closeLyt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/darker_gray"
android:weightSum="2" >
<TextView
android:id="#+id/cancelTxt"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="1dp"
android:layout_weight="1"
android:background="#fff"
android:gravity="center"
android:padding="5dp"
android:text="CANCEL"
android:textColor="#000"
android:textSize="20sp" />
<TextView
android:id="#+id/okTxt"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="1dp"
android:layout_weight="1"
android:background="#fff"
android:gravity="center"
android:padding="5dp"
android:text="OK"
android:textColor="#000"
android:textSize="20sp" />
</LinearLayout>
</LinearLayout>
And you can inflate this layout in custom dialog box and with the help of radio buttons you can choose service type
int serviceNumber = 0;
void OpenDialogService() {
final Dialog dialog = new Dialog(this);
dialog.getWindow();
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.pop_new_order2);
dialog.setCancelable(true);
dialog.setCanceledOnTouchOutside(true);
TextView headerTxt = (TextView) dialog.findViewById(R.id.headerTxt);
TextView okTxt = (TextView) dialog.findViewById(R.id.okTxt);
TextView cancelTxt = (TextView) dialog.findViewById(R.id.cancelTxt);
TextView primaryTxt = (TextView) dialog.findViewById(R.id.primaryTxt);
TextView otherTxt = (TextView) dialog.findViewById(R.id.otherTxt);
TextView primaryContentTxt = (TextView) dialog.findViewById(R.id.primaryContentTxt);
LinearLayout closeLyt = (LinearLayout) dialog.findViewById(R.id.closeLyt);
// Radio Buttons
final RadioGroup radio = (RadioGroup) dialog.findViewById(R.id.radioGroup1);
radio.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
View radioButton = radio.findViewById(checkedId);
int index = radio.indexOfChild(radioButton);
Toast.makeText(getApplicationContext(), "service" +index, 500).show();
serviceNumber = index+1;
}
});
headerTxt.setText("Pick Services");
//TODO change color here
// headerTxt.setBackgroundResource(R.drawable.bg_dialog_header_success);
// closeLyt.setBackgroundResource(R.color.selector_close_alert_dialog_success);
closeLyt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
cancelTxt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
okTxt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
Bundle b = getIntent().getExtras();
if (b == null)
b = new Bundle();
b.putString("service_id", String.valueOf(serviceNumber));
Toast.makeText(getApplicationContext(), "service " + String.valueOf(serviceNumber), 500).show();
//TODO Handle Activity Transition Here
// startActivity(new Intent(MainActivity.this,
// Step1.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP).putExtras(b));
// overridePendingTransition(R.anim.push_left_in,
// R.anim.push_left_out);
}
});
dialog.show();
}
Result
You can get the selected item id of RadioGroup using, radioGroup.getCheckedRadioButtonId() and use if-else to choose different strings.
int id = radioGroup.getCheckedRadioButtonId();
if(id == radioButton1)
{
b.putString("service_id", "1");
}
else if(id == radioButton1)
{
b.putString("service_id", "2");
}

Radio Buttons: Listener in XML or JAVA?

I decided to make an app in android for my science exhibition and I have reached a dead end!
I am trying to make a unit converter using radio buttons as the unit selection method.
All is fine but when I select another radio button, the app crashes!
I have no idea what is going on?
Here is my XML layout:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/TableLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="30dp" >
<RadioGroup
android:id="#+id/from"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left" >
<RadioButton
android:id="#+id/km"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:onClick="radioClicked"
android:text="KiloMeters" />
<RadioButton
android:id="#+id/m"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="radioClicked"
android:text="Meters" />
<RadioButton
android:id="#+id/cm"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="radioClicked"
android:text="Centimeters" />
</RadioGroup>
<Space
android:id="#+id/Space1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="fill_vertical" />
<EditText
android:id="#+id/KmValue"
android:layout_width="115dp"
android:layout_height="wrap_content"
android:layout_marginBottom="24dp"
android:layout_marginLeft="0dp"
android:ems="10"
android:inputType="numberDecimal" />
<RadioGroup
android:id="#+id/to"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RadioButton
android:id="#+id/mTo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="38dp"
android:checked="true"
android:onClick="radioClicked"
android:text="Meters" />
<RadioButton
android:id="#+id/cmTo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="radioClicked"
android:text="Cenitmeters" />
<RadioButton
android:id="#+id/mmTo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="radioClicked"
android:text="Millimeters" />
</RadioGroup>
<TextView
android:id="#+id/MValue"
android:layout_width="96dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="#+id/cButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Convert" />
</TableLayout>
And here is my Java Activity:
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
public class LengthFragment extends Fragment {
public LengthFragment(){}
double ratio = 1000;
int x=1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_length, container, false);
final EditText km = (EditText) rootView.findViewById(R.id.KmValue);
final TextView meter = (TextView) rootView.findViewById(R.id.MValue);
Button convert = (Button) rootView.findViewById(R.id.cButton);
convert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(km.getText().toString().isEmpty()) {
Toast.makeText(getActivity(), "Enter Something Buddy!", Toast.LENGTH_SHORT).show();
} else {
float k = Float.parseFloat(km.getText().toString());
double m = k*ratio;
meter.setText(""+m);
}
}
});
return rootView;
}
public void radioClicked(View view) {
boolean checked = ((RadioButton) view).isChecked();
switch(view.getId()) {
case R.id.km:
if (checked)
x=1;
break;
case R.id.m:
if (checked) {
x=2;
}
break;
case R.id.cm:
if (checked)
x=3;
break;
case R.id.mTo:
if (checked)
if(x==1) {
ratio=1000;
}
else if(x==2) {
ratio=1;
}
else if(x==3) {
ratio=0.01;
} else {
}
break;
case R.id.cmTo:
if (checked)
if(x==1) {
ratio=100000;
}
else if(x==2) {
ratio=100;
}
else if(x==3) {
ratio=1;
} else {
}
break;
case R.id.mmTo:
if (checked)
if(x==1) {
ratio=1000000;
}
else if(x==2) {
ratio=1000;
}
else if(x==3) {
ratio=10;
} else {
}
break;
}
}
}
I could post whatever may be required for the answer. Please help!
Instead of implementing OnClick to RadioButton just implement RadioGroup setOnCheckedChangeListener :
RadioGroup from = (RadioGroup) rootView.findViewById(R.id.from);
from.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup arg0, int id) {
if (id==R.id.km) {
x=1;
}else if(id==R.id.m){
x=2;
}else if(id==R.id.cm)
x=3;
}
});
Also apply same way setOnCheckedChangeListener for (to) RadioGroup and remove OnClick from xml.
Try adding a different listener for each radio group? Don't just rely on the onClickListener() for the Button.
Try having a setOnCheckedChangeListener for each radio group, e.g.
RadioGroup rgFrom = (RadioGroup) rootView.findViewById(R.id.from);
RadioGroup rgTo = (RadioGroup) rootView.findViewById(R.id.to);
rgFrom.setOnCheckedChangeListener(...)
rgTo.setOnCheckedChangeListener(...)
When the callback is made, i.e. onCheckedChanged, you can update your variables 'x' & 'ratio'
public void onCheckedChanged(RadioGroup group, int checkedId)
{
switch(group.getId())
{
case R.id.from:
// Do something to either 'x' or 'ratio'
break;
case R.id.to:
// Do something to either 'x' or 'ratio'
break;
}
}
Refer to the links provided for more detailed information on how to use it.
You can easily do the calculation/conversion when your Button is clicked, instead of having to deal with 'x' or 'ratio'.
Button convert = (Button) rootView.findViewById(R.id.cButton);
convert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do calculations/conversions based on the present state of the 2 radio groups
}
});

Android getting value from selected radiobutton

I have a piece of code with three RadioButtons within a RadioGroup. I want to set an onCheckedListener that will show the value of the RadioButton in a Toast. However what I have gotten so far is not working. How do I get the value of the RadioButton and display it in a Toast? This is my code:
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;
public class MainActivity extends Activity {
RadioGroup rg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RadioGroup rg = (RadioGroup) findViewById(R.id.radioGroup1);
final String value =
((RadioButton)findViewById(rg.getCheckedRadioButtonId()))
.getText().toString();
rg.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
Toast.makeText(getBaseContext(), value, Toast.LENGTH_SHORT).show();
}
});
}
}
XML file:
<RelativeLayout
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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<RadioGroup
android:id="#+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="152dp" >
<RadioButton
android:id="#+id/radio0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Choose 1" />
<RadioButton
android:id="#+id/radio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Choose 2" />
<RadioButton
android:id="#+id/radio2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Choose 3" />
</RadioGroup>
</RelativeLayout>
Tested and working. Check this
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
public class MyAndroidAppActivity extends Activity {
private RadioGroup radioGroup;
private RadioButton radioButton;
private Button btnDisplay;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
addListenerOnButton();
}
public void addListenerOnButton() {
radioGroup = (RadioGroup) findViewById(R.id.radio);
btnDisplay = (Button) findViewById(R.id.btnDisplay);
btnDisplay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// get selected radio button from radioGroup
int selectedId = radioGroup.getCheckedRadioButtonId();
// find the radiobutton by returned id
radioButton = (RadioButton) findViewById(selectedId);
Toast.makeText(MyAndroidAppActivity.this,
radioButton.getText(), Toast.LENGTH_SHORT).show();
}
});
}
}
xml
<RadioGroup
android:id="#+id/radio"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RadioButton
android:id="#+id/radioMale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/radio_male"
android:checked="true" />
<RadioButton
android:id="#+id/radioFemale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/radio_female" />
</RadioGroup>
In case, if you want to do some job on the selection of one of the radio buttons (without having any additional OK button or something), your code is fine, updated little.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RadioGroup rg = (RadioGroup) findViewById(R.id.radioGroup1);
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch(checkedId){
case R.id.radio0:
// do operations specific to this selection
break;
case R.id.radio1:
// do operations specific to this selection
break;
case R.id.radio2:
// do operations specific to this selection
break;
}
}
});
}
}
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId)
{
radioButton = (RadioButton) findViewById(checkedId);
Toast.makeText(getBaseContext(), radioButton.getText(), Toast.LENGTH_SHORT).show();
}
}
);
int genid=gender.getCheckedRadioButtonId();
RadioButton radioButton = (RadioButton) findViewById(genid);
String gender=radioButton.getText().toString();
Hope this works. You can convert your output to string in the above manner.
gender.getCheckedRadioButtonId(); - gender is the id of RadioGroup.
mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, #IdRes int checkedId) {
RadioButton radioButton = (RadioButton)group.findViewById(checkedId);
}
});
For anyone who is populating programmatically and looking to get an index, you might notice that the checkedId changes as you return to the activity/fragment and you re-add those radio buttons. One way to get around that is to set a tag with the index:
for(int i = 0; i < myNames.length; i++) {
rB = new RadioButton(getContext());
rB.setText(myNames[i]);
rB.setTag(i);
myRadioGroup.addView(rB,i);
}
Then in your listener:
myRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton radioButton = (RadioButton) group.findViewById(checkedId);
int mySelectedIndex = (int) radioButton.getTag();
}
});
just use getCheckedRadioButtonId() function to determine wether if anything is checked, if -1 is the return value, you can avoid showing toast
Radiogroup rgteam;
String team;
rgteam.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, #IdRes int checkedId) {
RadioButton rb= (RadioButton) findViewById(checkedId);
team = rb.getText().toString();
}
});
RadioGroup in XML
<?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="match_parent">
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Java"/>
</RadioGroup>
</RelativeLayout>
activity_main.xml
<?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="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="150dp"
android:layout_marginLeft="100dp"
android:textSize="18dp"
android:text="Select Your Course"
android:textStyle="bold"
android:id="#+id/txtView"/>
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/rdGroup"
android:layout_below="#+id/txtView">
<RadioButton
android:id="#+id/rdbJava"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginLeft="100dp"
android:text="Java"
android:onClick="onRadioButtonClicked"/>
<RadioButton
android:id="#+id/rdbPython"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginLeft="100dp"
android:text="Python"
android:onClick="onRadioButtonClicked"/>
<RadioButton
android:id="#+id/rdbAndroid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginLeft="100dp"
android:text="Android"
android:onClick="onRadioButtonClicked"/>
<RadioButton
android:id="#+id/rdbAngular"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginLeft="100dp"
android:text="AngularJS"
android:onClick="onRadioButtonClicked"/>
</RadioGroup>
<Button
android:id="#+id/getBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:layout_below="#+id/rdGroup"
android:text="Get Course" />
</RelativeLayout>
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
RadioButton android, java, angular, python;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
android = (RadioButton)findViewById(R.id.rdbAndroid);
angular = (RadioButton)findViewById(R.id.rdbAngular);
java = (RadioButton)findViewById(R.id.rdbJava);
python = (RadioButton)findViewById(R.id.rdbPython);
Button btn = (Button)findViewById(R.id.getBtn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String result = "Selected Course: ";
result+= (android.isChecked())?"Android":(angular.isChecked())?"AngularJS":(java.isChecked())?"Java":(python.isChecked())?"Python":"";
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show();
}
});
}
public void onRadioButtonClicked(View view) {
boolean checked = ((RadioButton) view).isChecked();
String str="";
// Check which radio button was clicked
switch(view.getId()) {
case R.id.rdbAndroid:
if(checked)
str = "Android Selected";
break;
case R.id.rdbAngular:
if(checked)
str = "AngularJS Selected";
break;
case R.id.rdbJava:
if(checked)
str = "Java Selected";
break;
case R.id.rdbPython:
if(checked)
str = "Python Selected";
break;
}
Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();
}
}
Thanks a lot to Chris.
This is my solution:
RadioGroup radgroup_opcionesEventos = null;
private static String[] arrayEventos = {
"CongestiĆ³n", "Derrumbe", "Accidente"
};
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
radgroup_opcionesEventos = (RadioGroup)findViewById(R.id.rg_opciones_evento);
int i=0;//a.new.ln
for(String evento : arrayEventos) {
//RadioButton nuevoRadio = crearRadioButton(evento);//a.old.ln
RadioButton nuevoRadio = crearRadioButton(evento,i);//a.new.ln
radgroup_opcionesEventos.addView(nuevoRadio,i);
}
RadioButton primerRadio = (RadioButton) radgroup_opcionesEventos.getChildAt(0);
primerRadio.setChecked(true);
}
private RadioButton crearRadioButton(String evento, int n)
{
//RadioButton nuevoRadio = new RadioButton(this);//a.old.ln
RadioButton nuevoRadio = new RadioButton(getApplicationContext());//a.new.ln
LinearLayout.LayoutParams params = new RadioGroup.LayoutParams(
RadioGroup.LayoutParams.WRAP_CONTENT,
RadioGroup.LayoutParams.WRAP_CONTENT);
nuevoRadio.setLayoutParams(params);
nuevoRadio.setText(evento);
nuevoRadio.setTag(evento);
return nuevoRadio;
}
#Override
protected void onResume()
{
radgroup_opcionesEventos.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton radioButton = (RadioButton) group.findViewById(checkedId);
//int mySelectedIndex = (int) radioButton.getTag();
String mySelectedIndex = radioButton.getTag().toString();
}
});
super.onResume();
}
I have had problems getting radio buttons id's as well when the RadioButtons are dynamically generated. It does not seem to work if you try to manually set the ID's using RadioButton.setId(). What worked for me was to use View.getChildAt() and View.getParent() in order to iterate through the radio buttons and determine which one was checked. All you need is to first get the RadioGroup via findViewById(R.id.myRadioGroup) and then iterate through it's children. You'll know as you iterate through which button you are on, and you can simply use RadioButton.isChecked() to determine if that is the button that was checked.

Inflated layout's buttons onClick listener not working

All my other onClick methods work except the ones in which I have to inflate the layout to get the button! What am I doing wrong! Here is some code:
package com.games.think;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.TableLayout;
public class Think extends Activity{
//What question are we on?
int question = 1;
//What level are we on?
String lvl ="1";
//Radio buttons we need to access them global
RadioButton lvl1;
RadioButton lvl2;
RadioButton lvl3;
RadioButton lvl4;
RadioButton lvl5;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//play
Button play = (Button)findViewById(R.id.play);
play.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
playOnClick(v);
}
});
//level
Button level = (Button)findViewById(R.id.level);
level.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
levelOnClick(v);
}
});
//setLevel
LayoutInflater inflater = LayoutInflater.from(this);
TableLayout tbl = new TableLayout(this);
View playv = inflater.inflate(R.layout.level, null);
Button updateLevel = (Button) playv.findViewById(R.id.updateLevel);
tbl.addView(updateLevel);
updateLevel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateLevelOnClick(v);
}
});
View levelv = inflater.inflate(R.layout.play, null);
Button gotomenu = (Button) levelv.findViewById(R.id.tomenu);
gotomenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
toMenuOnClick(v);
}
});
//Radio Buttons
lvl1 = (RadioButton) levelv.findViewById(R.id.lvl1);
lvl2 = (RadioButton) levelv.findViewById(R.id.lvl2);
lvl3 = (RadioButton) levelv.findViewById(R.id.lvl3);
lvl4 = (RadioButton) levelv.findViewById(R.id.lvl4);
lvl5 = (RadioButton) levelv.findViewById(R.id.lvl5);
//tomenu
lvl = getLevel();
if(lvl.equals("-1")) {
lvl=getLevel();
}
}
protected void toMenuOnClick(View v) {
setContentView(R.layout.main);
}
protected void updateLevelOnClick(View v) {
setContentView(R.layout.main);
}
protected void levelOnClick(View v) {
setContentView(R.layout.level);
if(lvl.equals("1")) {
lvl1.setChecked(true);
}
if(lvl.equals("2")) {
lvl2.setChecked(true);
}
if(lvl.equals("3")) {
lvl3.setChecked(true);
}
if(lvl.equals("4")) {
lvl4.setChecked(true);
}
if(lvl.equals("5")) {
lvl5.setChecked(true);
}
}
protected void playOnClick(View v) {
setContentView(R.layout.play);
setQuestion();
}
private String getLevel() {
String FILENAME = "think_level";
FileInputStream fis;
byte[] buffer = new byte[1000];
try {
fis = openFileInput(FILENAME);
} catch (FileNotFoundException e) {
setLevel("1");
return "-1";
}
try {
fis.read(buffer,0,1000);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String level = buffer.toString();
return level;
}
private void setLevel(String _level) {
String FILENAME = "think_level";
String level = _level;
FileOutputStream fos;
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(level.getBytes());
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private void setQuestion() {
}
}
Here are my xml files:
Main.xml:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout android:id="#+id/tableLayout1" android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android">
<ImageView android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="#+id/imageView1" android:src="#drawable/think" android:scaleType="fitCenter"></ImageView>
<Button android:id="#+id/play" android:text="Play" android:layout_height="wrap_content" android:layout_width="wrap_content" ></Button>
<Button android:text="Level" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="#+id/level"></Button>
</TableLayout>
Here is my level.xml
<?xml version="1.0" encoding="utf-8"?>
<TableLayout android:id="#+id/tableLayout1" android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android">
<TableRow android:id="#+id/tableRow1" android:layout_width="wrap_content" android:layout_height="wrap_content">
<TextView android:text="Level:" android:id="#+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
</TableRow>
<TableRow android:id="#+id/tableRow2" android:layout_width="wrap_content" android:layout_height="wrap_content">
<RadioGroup android:id="#+id/radioGroup1" android:layout_width="wrap_content" android:layout_height="wrap_content">
<RadioButton android:id="#+id/lvl1" android:text="Level 1" android:layout_height="wrap_content" android:checked="true" android:layout_width="wrap_content"></RadioButton>
<RadioButton android:id="#+id/lvl2" android:text="Level 2" android:layout_height="wrap_content" android:layout_width="wrap_content"></RadioButton>
<RadioButton android:id="#+id/lvl3" android:text="Level 3" android:layout_height="wrap_content" android:layout_width="wrap_content"></RadioButton>
<RadioButton android:id="#+id/lvl4" android:text="Level 4" android:layout_height="wrap_content" android:layout_width="wrap_content"></RadioButton>
<RadioButton android:id="#+id/lvl5" android:text="Level 5" android:layout_height="wrap_content" android:layout_width="wrap_content"></RadioButton>
</RadioGroup>
</TableRow>
<Button android:text="Set Level" android:id="#+id/updateLevel" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</TableLayout>
Here is play.xml:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ScrollView android:id="#+id/scrollView1" android:layout_width="wrap_content" android:layout_height="wrap_content">
<TextView android:text="TextView" android:id="#+id/question" android:layout_height="wrap_content" android:layout_width="wrap_content"></TextView>
</ScrollView>
<RadioGroup android:id="#+id/radioGroup1" android:layout_width="wrap_content" android:layout_height="wrap_content" >
<RadioButton android:id="#+id/radioButton1" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="RadioButton"></RadioButton>
<RadioButton android:id="#+id/radioButton2" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="RadioButton"></RadioButton>
<RadioButton android:id="#+id/radioButton3" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="RadioButton"></RadioButton>
</RadioGroup>
<Button android:id="#+id/go" android:text="Go" android:layout_height="wrap_content" android:layout_width="wrap_content"></Button>
<Button android:id="#+id/tomenu" android:text="Back To Menu" android:layout_height="wrap_content" android:layout_width="wrap_content"></Button>
</TableLayout>
The problem is that the view you are adding does not have a parent and therefore is not able to receive click events. Currently you're inflating the view using
View playv = inflater.inflate(R.layout.level, null);
You'll want to place a parent view in that second argument.
View playv = inflater.inflate(R.layout.level, parentView, false);
This will allow you to use a parent view but not actually attach it.
So the buttons are in your level and play layouts, and you're inflating those layouts, but it doesn't look like you're ever adding the layouts to the your main view/layout. Are you actually able to see those two layouts you are inflating?
inflation is async method, can you try to add the click listener after its inflated
//only inflate in oncreate / onresume
inflater.inflate(
R.layout.play, // resource
this, // root
true); //attach to root
//overide onFinishInflate and get the view here
protected void onFinishInflate() {
super.onFinishInflate();
Button gotomenu = (Button) levelv.findViewById(R.id.tomenu);
gotomenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
toMenuOnClick(v);
}
});
}
There is no apparent reason why this should not work.
Any runtime created views must be added to your linearlayout(or any other parent layout)
using :
linearLayoutMain.addView(updateLevel);
Have you used this buttons in any of the linear layouts in your xml file i.e. does these buttons appear when you reach the corresponding activity?
You should be seeing the exception at tbl.addView(updateLevel);, because you are trying to add a view whose parent is already specified.
Are you not seeing this exception ?
If You want item value on item click just use .setTag(some value); and getTag();
RelativeLayout firstContactRlayout = (RelativeLayout) myLayout.findViewById(R.id.firstContactRlayout);
firstContactRlayout.setTag(number);
firstContactRlayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String gettags = (String) v.getTag();
Log.e("gettags", "--" + gettags);
}
});
Try this after tbl.addView(updateLevel); 0 of tbl.getChildAt(0) may change:
tbl.getChildAt(0).findViewById(R.id.updateLevel).setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
updateLevelOnClick(v);
}
});

Categories