I am working on quiz application in android. We have created Select.java page which displays the questions and options(with radio buttons) from sqlite database. Also we created a header.java file for displaying buttons i.e back and next buttons for the Select.java page.
Here we need to get the selected radio button id and need to send that to Header class. Because header class consists of the next button onclick action. Once the next button is clicked the selected radio button value has to be stored in arraylist. We created radio buttons in Select.java class. So my question is how to get the selected radio button id into that next button click action. Please help me regarding this.
Thanks in Advance.
Your layout xml file should be like this
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<RadioGroup
android:orientation="vertical"
android:id="#+id/radiogroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/option1"
android:text="Option1"
/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/option2"
android:text="Option2"
/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/option3"
android:text="Option3"
/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/option4"
android:text="Option4"
/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/option5"
android:text="Option5"
/>
</RadioGroup>
</LinearLayout>
Add the below ode in your Activity
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radiogroup);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId)
{
RadioButton checkedRadioButton = (RadioButton) findViewById(checkedId);
String text = checkedRadioButton.getText().toString();
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}
});
I know it's a old question but i don't see my answer in anywhere and i found it more simple than others..
so here we go:
int myRadioChecked;
if(radioGroup.getCheckedRadioButtonId() == findViewById(R.id.YOUR_RADIO_BUTTON).getId()) {
/**Do Stuff*/
//ex.: myRadioChecked = 1;
}
final RadioGroup radioGroup = (RadioGroup) findViewById(R.id.MyRadioGroup);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup arg0, int arg1) {
int selectedId = radioGroup.getCheckedRadioButtonId();
Log.i("ID", String.valueOf(selectedId));
}
});
In RadioGroup Class you can use method getCheckedRadioButtonId();
RadioGroup rg = findViewById(R.id.radioGroup);
rg.getCheckedRadioButtonId();
Returns the identifier of the selected radio button in this group. Upon empty selection, the returned value is -1.
Hmmm, just add one more member variable in UserBO to store selected answer.
Class UserBO {
private int userID;
private String userName;
private String question;
private String option1;
private String option2;
private String option3;
private int answerID;
//create getter and setters for above member variables
}
then within onclick listener of Adapter class, do like as following
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup,
int radioButtonID) {
switch(radioButtonID) {
case R.id.option1:
listItem.setAnswerID(1);
break;
case R.id.option2:
listItem.setAnswerID(2);
break;
}
}
});
then change your header constructor to receive userarraylist (which contains user details with answer)
ArrayList<USerBO> userList;
Header(Context context, AttributeSet attrs, ArrayList<UserBO> userALt) {
userList = userAL;
}
//on next button click
onclick() {
for(UserBO userObj: userList) {
if (userObj.getAnswerID != 0)
Log.d("AnswerID", userObj.getAnswerID);
}
}
it just like sudo code.. i hope this will help u..
you can get the id of selected button by the following this.Here
int position = group.indexOfChild(radioButton);
will give you the id.Also you can to Toast to see id like this
Toast.makeText(MainActivity.this,"Id of radio button"+position+, Toast.LENGTH_SHORT).show();
This will pop up - "Id of radio button you clicked is 0" if you clicked first button.
This is the best way:
RadioButton button = findViewById(v.getId());
Related
In my Android application, I want to create a fragment that works like a keypad. I have one function which handle onClick for all 9 keys. I want to know is there anyway to write just one function to handle onLongClick for all these 9 keys too.
here is layout xml :
<Button
android:id="#id/testButton"
android:layout_width="70dp"
android:layout_height="55dp"
android:layout_margin="2dp"
android:background="#drawable/keypad_round_button"
android:text="1"
android:textColor="#color/black_1"
android:onClick="keypadSetNote"
android:longClickable="true"/>
<Button
android:id="#id/testButton"
android:layout_width="70dp"
android:layout_height="55dp"
android:layout_margin="2dp"
android:background="#drawable/keypad_round_button"
android:text="2"
android:longClickable="true"
android:textColor="#color/black_1"
android:onClick="keypadSetNote"
/>
Here is OnlongClick listener :
Button button = (Button) findViewById(R.id.testButton);
button.setOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View v) {
Button clickedButton = (Button) v;
String buttonText = clickedButton.getText().toString();
Log.v(TAG, "button long pressed --> " + buttonText);
return true;
}
});
I gave all keys same ID to handle all onLongClick actions in one function, but it just work for the first key. Is there anyway to define something like group button in Android ??? Or I have to write OnLongClick listener for all of them separately ???
Just create a named function instead of an anonymous one:
View.OnLongClickListener listener = new View.OnLongClickListener() {
public boolean onLongClick(View v) {
Button clickedButton = (Button) v;
String buttonText = clickedButton.getText().toString();
Log.v(TAG, "button long pressed --> " + buttonText);
return true;
}
};
button1.setOnLongClickListener(listener);
button2.setOnLongClickListener(listener);
button3.setOnLongClickListener(listener);
And, altough you don't asked it, we must warn you: As #AndyRes says, your buttons must have differents ids. Having the same ID doesn't mean that getting the button by id will return all buttons, only will return the first button with that ID, that's because it only works with the first button.
Buttons should have different ids:
<Button
android:id="#id/testButton1"
//... />
<Button
android:id="#id/testButton2"
//... />
<Button
android:id="#id/testButton3"
//... />
Now, to set the listener for all, a solution would be to get the id of all buttons in an array, and then use a "for" loop to set the listener for each.
Like this:
// Store the id of buttons in an array
int[] ids={R.id.testButton1, R.id.testButton2,R.id.testButton3};
// loop through the array, find the button with respective id and set the listener
for(int i=0; i<ids.length; i++){
Button button = (Button) findViewById(ids[i]);
button.setOnLongClickListener(longClickListener);
}
View.OnLongClickListener longClickListener = new View.OnLongClickListener() {
public boolean onLongClick(View v) {
// .....
return true;
}
};
if your buttons are in the LinearLayout, in the RelativeLayour or in the other. And you have very many buttons.
View.OnLongClickListener listener = new View.OnLongClickListener() {
public boolean onLongClick(View v) {
Log.d("ID", ""+v.getId());
switch (v.getId())
{
case R.id.button1:
//do something for button1
break;
case R.id.button2:
//do something for button2
break;
...
}
return true;
}
};
LinearLayout layout=(LinearLayout)findViewById(R.id.IdOfLinearLayout);
for(int i=0;i<layout.getChildCount();i++){
layout.getChildAt(i).setOnLongClickListener(listener);
}
xml file for example...
<LinearLayout
android:id=#+id/IdOfLinearLayout"....>
<Button
android:id="#+id/button1"
android:layout_width=...
android:layout_height=...
.../>
<Button
android:id="#+id/button2"
... />
....
<Button
android:id="#+id/buttonN"
.../>
</LinearLayout>
I want to increment the value in textview on button click event i hv written the code for the same but when i press +Button it increments the textview below it not on same textview.
there r two buttons + and -
on +button value should increment and
on -Button value should decremnt of textview in listview of android
here is my sample code ...
this my xml file
<TextView
android:id="#+id/add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/minus"
android:layout_alignBottom="#+id/minus"
android:layout_toLeftOf="#+id/qty"
android:onClick="onClick"
android:text="+"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textSize="20dp"
android:textStyle="bold" />
and the code in adapter is below
text5.setOnClickListener(new OnClickListener()
{
public void onClick(View v) {
String qty=text4.getText().toString();
System.out.println("orginal string :"+qty);
int mn=Integer.parseInt(qty);
System.out.println("integer format : "+mn);
int qty1=mn+1;
System.out.println("after increment :"+qty1);
String s = new Integer(qty1).toString();
System.out.println("final string :"+s);
text4.setText(""+qty1);
App.qty=s;
}
});
text6.setOnClickListener(new OnClickListener()
{
public void onClick(View v) {
String qty=text4.getText().toString();
int mn=Integer.parseInt(qty);
int qty1=mn--;
text4.setText(""+qty1);
String s = new Integer(qty1).toString();
text4.setText(s);
App.qty=s;
}
});
Any help will be appreciated Thanks.
i used arraylist instead of string array ..that sloved my problem
I have a button's onClickListener that needs to detect which radiobutton was selected when the user clicks the button. Currently, the Log.v you see below in the onClickListener is not returning a useless bit of info:
This is clicking submit three times with a different radio selected each time:
04-27 19:24:42.417: V/submit(1564): 1094168584
04-27 19:24:45.048: V/submit(1564): 1094167752
04-27 19:24:47.348: V/submit(1564): 1094211304
So, I need to know which radioButton is actually selected - is there a way to get the object of the radiobutton? I want to be able to get it's id# from XML, as well as its current text.
Here's the relevant code:
public void buildQuestions(JSONObject question) throws JSONException {
radioGroup = (RadioGroup) questionBox.findViewById(R.id.responseRadioGroup);
Button chartsButton = (Button) questionBox.findViewById(R.id.chartsButton);
chartsButton.setTag(question);
Button submitButton = (Button) questionBox.findViewById(R.id.submitButton);
chartsButton.setOnClickListener(chartsListener);
submitButton.setOnClickListener(submitListener);
TagObj tagObj = new TagObj(question, radioGroup);
submitButton.setTag(tagObj);
}
public OnClickListener submitListener = new OnClickListener() {
public void onClick(View v) {
userFunctions = new UserFunctions();
if (userFunctions.isUserLoggedIn(activity)) {
TagObj tagObject = (TagObj) v.getTag();
RadioGroup radioGroup = tagObject.getRadioGroup();
JSONObject question = tagObject.getQuestion();
Log.v("submit", Integer.toString(radioGroup.getCheckedRadioButtonId()));
SubmitTask submitTask = new SubmitTask((Polling) activity, question);
submitTask.execute();
}
}
};
getCheckedRadioButtonId() returns the id of the RadioButton(or -1 if no RadioButtons are checked) that is checked in the Radiogroup. If you set distinct ids to the RadioButons in the layout then you will try to match those ids with the return of the method to see which one is checked:
//field in the class
private static final int RB1_ID = 1000;//first radio button id
private static final int RB2_ID = 1001;//second radio button id
private static final int RB3_ID = 1002;//third radio button id
//create the RadioButton
RadioButton rb1 = new RadioButton(this);
//set an id
rb1.setId(RB1_ID);
int btn = radioGroup.getCheckedRadioButtonId();
switch (btn) {
case RB1_ID:
// the first RadioButton is checked.
break;
//other checks for the other RadioButtons ids from the RadioGroup
case -1:
// no RadioButton is checked inthe Radiogroup
break;
}
store the checked ID, then compare it to each button using the function radioButton.getID() using a switch statement or if-else chains
I am setting initial checked radioButton in RadioGroup xml
<RadioGroup
android:id="#+id/rgCustomized"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:layout_marginTop="8dp"
android:checkedButton="#+id/rbNotCustomized"
android:orientation="horizontal">
<RadioButton
android:id="#+id/rbCustomized"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="50dp"
android:text="#string/yes" />
<RadioButton
android:id="#+id/rbNotCustomized"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/no" />
</RadioGroup>
And I identify which radioButton is selected like this
rgCustomized.checkedRadioButtonId==rbCustomized.id
I think relying on what radioGroup.getCheckedRadioButtonId() returns is not good practice if you want to store it into the database or to use it.
Because:
getCheckedRadioButtonId() value will keep changing for each RadioButton and if there are two similar values (two views in the same hierarchy) Android will choose the first one. Unless you provided a unique Ids with method generateViewId() and set it to the view with setId().
getCheckedRadioButtonId() will return unknown value.
Therefore
Switching on radioGroup.getCheckedRadioButtonId() and implement your custom values to each selection then use that custom value, not the View Id.
Example to use values from selected Radio Button:
int selected = -1;
switch (radioGroup.getCheckedRadioButtonId()) {
case R.id.one_radioButton:
selected = 0;
break;
case R.id.two_radioButton:
selected = 1;
break;
case R.id.three_radioButton:
selected = 2;
break;
}
// return a custom value you specific
Log.d(TAG, "selectedBox: " + selectedBox);
// return a random unknown number value
Log.d(TAG, "radioGroup.getCheckedRadioButtonId(): " + radioGroup.getCheckedRadioButtonId());
Example to populate selected RadioButton to UI:
switch (selected) {
case 0:
oneRadioButton.setChecked(true);
break;
case 1:
twoRadioButton.setChecked(true);
break;
case 2:
threeRadioButton.setChecked(true);
break;
}
I'm using radio group but RadioGroup onClick event is not firing and
the method getCheckedRadiobuttonID() is returning null. Here is the element in my layout:
<RadioGroup
android:id="#+id/RG1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:onClick="onRGClick" >
Method
public void onRGClick(View v) {
Toast.makeText(this, "Test ", 1000).show();
}
This problem can be solved using the following
RadioGroup rg = (RadioGroup) findViewById(R.id.radioGroup1);
rg.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(RadioGroup group, int checkedId)
{
switch(checkedId)
{
case R.id.radio0:
// TODO Something
break;
case R.id.radio1:
// TODO Something
break;
case R.id.radio2:
// TODO Something
break;
}
}
});
Alternatively
You can use custom ids rather than default one
RadioGroup rg = (RadioGroup) findViewById(R.id.radioGroup1);
rg.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(RadioGroup group, int checkedId)
{
switch(checkedId)
{
case R.id.male:
// TODO Something
break;
case R.id.female:
// TODO Something
break;
case R.id.other:
// TODO Something
break;
}
}
});
Actually I think you do not need to add android:clickable="true" or click listener. You can declare RadioGroup.OnCheckedChangeListener which will listen for change of the selection. Please see this thread for example how you can use that.
EDIT : I did some changes in your code and its working for me. onClick works for all the views. Here in your code, Rgroup's width is wrap_content, so if you have put RadioButtons inside the RG (which will completely overlap the RG), your clicks would be consumed by the RadioButtons (and not the Rgroup). I made the Rgroup's width to fill_parent and the click was getting executed. Here is my sample so that you can try it out.
<RadioGroup android:onClick="onRGClick" ndroid:text="RadioButton"
android:id="#+id/radioGroup1" android:layout_width="fill_parent" android:layout_height="wrap_content">
<RadioButton android:text="RadioButton" android:id="#+id/radioButton2" android:layout_width="wrap_content" android:layout_height="wrap_content"></RadioButton>
</RadioGroup>
And here is the Activity:
public class Hello extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void onRGClick(View v){
Toast.makeText(this, "Test ", Toast.LENGTH_LONG).show();
}
Just click anywhere to the right of the RadioButton, and you will see the Toast.
Although for general purposes,OnCheckedChangeListener is more useful.
Hope this helps you.
The other way is to assign your method to onClick property of each RadioButton. Then check for the view id. For instance,
public void onRGClick(View v) {
int id = view.getId();
if (id == R.id.radioButtonId) {
//Do something
}
}
I have two RadioButtons inside a RadioGroup. I want to set OnClickListener on those RadioButtons. Depending on which RadioButton is clicked, I want to change the text of an EditText. How can I achieve this?
I'd think a better way is to use RadioGroup and set the listener on this to change and update the View accordingly (saves you having 2 or 3 or 4 etc listeners).
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.yourRadioGroup);
radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// checkedId is the RadioButton selected
}
});
Hope this will help you...
RadioButton rb = (RadioButton) findViewById(R.id.yourFirstRadioButton);
rb.setOnClickListener(first_radio_listener);
and
OnClickListener first_radio_listener = new OnClickListener (){
public void onClick(View v) {
//Your Implementaions...
}
};
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
public void onCheckedChanged(RadioGroup group, int checkedId) {
// checkedId is the RadioButton selected
RadioButton rb=(RadioButton)findViewById(checkedId);
textViewChoice.setText("You Selected " + rb.getText());
//Toast.makeText(getApplicationContext(), rb.getText(), Toast.LENGTH_SHORT).show();
}
});
The question was about Detecting which radio button is clicked, this is how you can get which button is clicked
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);
// Add logic here
switch (index) {
case 0: // first button
Toast.makeText(getApplicationContext(), "Selected button number " + index, 500).show();
break;
case 1: // secondbutton
Toast.makeText(getApplicationContext(), "Selected button number " + index, 500).show();
break;
}
}
});
For Kotlin Here is added the lambda expression and Optimized the Code.
radioGroup.setOnCheckedChangeListener { radioGroup, optionId ->
run {
when (optionId) {
R.id.radioButton1 -> {
// do something when radio button 1 is selected
}
R.id.radioButton2 -> {
// do something when radio button 2 is selected
}
// add more cases here to handle other buttons in the your RadioGroup
}
}
}
Hope this will help you. Thanks!
You could also add listener from XML layout: android:onClick="onRadioButtonClicked" in your <RadioButton/> tag.
<RadioButton android:id="#+id/radio_pirates"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/pirates"
android:onClick="onRadioButtonClicked"/>
See Android developer SDK- Radio Buttons for details.
Since this question isn't specific to Java, I would like to add how you can do it in Kotlin:
radio_group_id.setOnCheckedChangeListener({ radioGroup, optionId -> {
when (optionId) {
R.id.radio_button_1 -> {
// do something when radio button 1 is selected
}
// add more cases here to handle other buttons in the RadioGroup
}
}
})
Here radio_group_id is the assigned android:id of the concerned RadioGroup. To use it this way you would need to import kotlinx.android.synthetic.main.your_layout_name.* in your activity's Kotlin file. Also note that in case the radioGroup lambda parameter is unused, it can be replaced with _ (an underscore) since Kotlin 1.1.
Just in case someone else was struggeling with the accepted answer:
There are different OnCheckedChangeListener-Interfaces. I added to first one to see if a CheckBox was changed.
import android.widget.CompoundButton.OnCheckedChangeListener;
vs
import android.widget.RadioGroup.OnCheckedChangeListener;
When adding the snippet from Ricky I had errors:
The method setOnCheckedChangeListener(RadioGroup.OnCheckedChangeListener) in the type RadioGroup is not applicable for the arguments (new CompoundButton.OnCheckedChangeListener(){})
Can be fixed with answer from Ali :
new RadioGroup.OnCheckedChangeListener()
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.yourRadioGroup);
radioGroup.setOnClickListener(v -> {
// get selected radio button from radioGroup
int selectedId = radioGroup.getCheckedRadioButtonId();
// find the radiobutton by returned id
radioButton = findViewById(selectedId);
String slectedValue=radioButton.getText()
});