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.
Related
I am trying to add a search bar that enables me to search by buttons, search between btn1 and btn2 and btn3. I tried a lot of codes but all of them were focused on TextView and not on buttons. So hope to help me and if I missed details please let me know to describe more.
The two files (.java and .xml) are typed below. thank you.
file.java
package com.example.myapp1;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DownloadManager;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
SearchView sv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setTitle("My First App");
Button btn1 = findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, MainActivity2.class);
startActivity(intent);
}});
Button btn2 = findViewById(R.id.btn2);
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, MainActivity3.class);
startActivity(intent);
}});
Button btn3 = findViewById(R.id.btn3);
btn3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, MainActivity4.class);
startActivity(intent);
}});
List<Button> buttonList = new ArrayList<>();
buttonList.add(view.findViewById(R.id.btn1));
buttonList.add(view.findViewById(R.id.btn2));
buttonList.add(view.findViewById(R.id.btn3));
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
for(int i = 0; i < buttonList.size(); i++) {
String buttonText = (String) buttonList.get(i).getText();
if(buttonText.toLowerCase(Locale.ROOT).equals(s.toLowerCase())) {
buttonList.get(i).setVisibility(View.VISIBLE);
} else {
buttonList.get(i).setVisibility(View.INVISIBLE);
}
}
return false;
}
#Override
public boolean onQueryTextChange(String s) {
if(s.isEmpty()) {
for(int i = 0; i < buttonList.size(); i++) {
buttonList.get(i).setVisibility(View.VISIBLE);
}
}
return false;
}
});
}
}
file.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
tools:context=".MainActivity"
tools:ignore="ExtraText"
android:orientation="horizontal">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
android:layout_marginHorizontal="10dp"
android:orientation="vertical"
android:weightSum="2">
<Button
android:id="#+id/btn1"
android:layout_width="match_parent"
android:layout_height="90dp"
android:textAllCaps="false"
android:textSize="25dp"
android:layout_marginHorizontal="10dp"
android:layout_weight="1"
android:background="#drawable/gradient"
android:textColor="#color/white"
android:text="Absolute Pressure" />
<Space
android:layout_width="match_parent"
android:layout_height="15dp"
android:layout_weight="1" />
<Button
android:id="#+id/btn2"
android:layout_width="match_parent"
android:layout_height="90dp"
android:textAllCaps="false"
android:textSize="25dp"
android:layout_marginHorizontal="10dp"
android:layout_weight="1"
android:background="#drawable/gradient"
android:textColor="#color/white"
android:text="Acoustic Flowmeter" />
<Space
android:layout_width="match_parent"
android:layout_height="15dp"
android:layout_weight="1" />
<Button
android:id="#+id/btn3"
android:layout_width="match_parent"
android:layout_height="90dp"
android:textAllCaps="false"
android:textSize="25dp"
android:layout_marginHorizontal="10dp"
android:layout_weight="1"
android:background="#drawable/gradient"
android:textColor="#color/white"
android:text="Bernoulli Number" />
<Space
android:layout_width="match_parent"
android:layout_height="15dp"
android:layout_weight="1" />
</LinearLayout>
</LinearLayout>
What do you mean by search by buttons? Are you looking to search the text that is held within the button?
Here is a way you can go about this:
Make a list that contains all the instances of your buttons.
List(findViewById(R.id.btn1), etc)
List<Button> buttonList = new ArrayList<>();
buttonList.add(view.findViewById(R.id.button_search1));
buttonList.add(view.findViewById(R.id.button_search2));
buttonList.add(view.findViewById(R.id.button_search3));
We are going to use the listeners available to the search view to do the work.
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
// You can use this for when the submit is clicked
#Override
public boolean onQueryTextSubmit(String s) {
// We loop over the button list
for(int i = 0; i < buttonList.size(); i++) {
// We get the text of the button
String buttonText = (String) buttonList.get(i).getText();
// We turn both the button text and search result to lowercase
// So that results are not case sensitive
// If they match
if(buttonText.toLowerCase(Locale.ROOT).equals(s.toLowerCase())) {
// We make button visible
buttonList.get(i).setVisibility(View.VISIBLE);
} else {
// If it doesn't, we make invisible
buttonList.get(i).setVisibility(View.INVISIBLE);
}
}
return false;
}
// You can use this when the text is changing.
#Override
public boolean onQueryTextChange(String s) {
// If text is empty, reset results
if(s.isEmpty()) {
for(int i = 0; i < buttonList.size(); i++) {
buttonList.get(i).setVisibility(View.VISIBLE);
}
}
return false;
}
});
I am new to here and java. I am developing an android app with radio buttons which calculates the SGPA of a student. Every subject has it's own credits which gets multiplies by the respective grade and after the addition of all products of the subject, The sum is divided by the total credits...
So far i've completed the xml code properly but i am stuck in the java main activity... I just need an example of only one button or subject and rest i will do on my own... I want to use switch case to first check which radio button is clicked and then do the respective calculations.
XML CODE
<TextView
android:id="#+id/maths"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#F44336"
android:text="MATHEMATICS"
android:textAlignment="center"
android:textAllCaps="true"
android:textAppearance="?android:textAppearanceLarge"
android:textStyle="bold" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#F44336"
android:orientation="horizontal">
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="7"
android:orientation="horizontal">
<RadioButton
android:id="#+id/Omaths"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="O"
android:onClick="onRadioButtonClicked"/>
<RadioButton
android:id="#+id/Aplusmaths"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="A+"
android:onClick="onRadioButtonClicked"/>
<RadioButton
android:id="#+id/Amaths"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="A"
android:onClick="onRadioButtonClicked"/>
<RadioButton
android:id="#+id/Bplusmaths"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="B+"
android:onClick="onRadioButtonClicked"/>
<RadioButton
android:id="#+id/Bmaths"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="B"
android:onClick="onRadioButtonClicked"/>
<RadioButton
android:id="#+id/Cmaths"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="C"
android:onClick="onRadioButtonClicked"/>
<RadioButton
android:id="#+id/Pmaths"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="P"
android:onClick="onRadioButtonClicked"/>
</RadioGroup>
</LinearLayout>
AND THE JAVA MAIN ACTIVITY CODE IS
package droidmentor.bnv_with_viewpager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.RadioButton;
import android.widget.TextView;
import droidmentor.bnv_with_viewpager.Fragment.CallsFragment;
import droidmentor.bnv_with_viewpager.Fragment.ChatFragment;
import droidmentor.bnv_with_viewpager.Fragment.ContactsFragment;
import static droidmentor.bnv_with_viewpager.R.id.Amaths;
import static droidmentor.bnv_with_viewpager.R.id.Bmaths;
import static droidmentor.bnv_with_viewpager.R.id.Bplusmaths;
import static droidmentor.bnv_with_viewpager.R.id.Cmaths;
import static droidmentor.bnv_with_viewpager.R.id.Pmaths;
public class MainActivity extends AppCompatActivity {
BottomNavigationView bottomNavigationView;
//This is our viewPager
private ViewPager viewPager;
//Fragments
ChatFragment chatFragment;
CallsFragment callsFragment;
ContactsFragment contactsFragment;
MenuItem prevMenuItem;
//Instance Variables For Each Subject
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Initializing viewPager
viewPager = (ViewPager) findViewById(R.id.viewpager);
//Initializing the bottomNavigationView
bottomNavigationView = (BottomNavigationView)findViewById(R.id.bottom_navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.action_call:
viewPager.setCurrentItem(0);
break;
case R.id.action_chat:
viewPager.setCurrentItem(1);
break;
case R.id.action_contact:
viewPager.setCurrentItem(2);
break;
}
return false;
}
});
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
if (prevMenuItem != null) {
prevMenuItem.setChecked(false);
}
else
{
bottomNavigationView.getMenu().getItem(0).setChecked(false);
}
Log.d("page", "onPageSelected: "+position);
bottomNavigationView.getMenu().getItem(position).setChecked(true);
prevMenuItem = bottomNavigationView.getMenu().getItem(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
/* //Disable ViewPager Swipe
viewPager.setOnTouchListener(new View.OnTouchListener()
{
#Override
public boolean onTouch(View v, MotionEvent event)
{
return true;
}
});
*/
setupViewPager(viewPager);
}
//This method is called when button is pressed
public void calculate(View view) {
display(9);
}
//This method returns the SGPA
private void display(int number) {
TextView sgpa = (TextView) findViewById(R.id.sgpa);
sgpa.setText("" + number);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
callsFragment=new CallsFragment();
chatFragment=new ChatFragment();
contactsFragment=new ContactsFragment();
adapter.addFragment(callsFragment);
adapter.addFragment(chatFragment);
adapter.addFragment(contactsFragment);
viewPager.setAdapter(adapter);
}
}
I know i can use the user input method with edit text but i have to use radio buttons... :)
try do this to get selected button:
int radioButtonID = radioButtonGroup.getCheckedRadioButtonId();
View radioButton = radioButtonGroup.findViewById(radioButtonID);
int idx = radioButtonGroup.indexOfChild(radioButton);
Note that if you use textview or other view inside radioGroup not equal to radiobutton you get wrong index.
To get the text of selected button:
RadioButton r = (RadioButton) radioButtonGroup.getChildAt(idx);
String selectedtext = r.getText().toString();
I'm not really sure why my application won't start up, I get no errors and I have no idea what's going on? I'm pretty new to android and this is just a basic calculator, but it keeps crashing every time I start it up.
***************Main Activity.java**********************
package com.example.alex.myapplication;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Something(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
*******************Something.java******************
package com.example.alex.myapplication;
import android.app.Activity;
import android.view.View;
import android.widget.EditText;
import android.widget.Button;
public class Something extends Activity {
private Button add,subtract,multiply,devide;
private EditText editA, editB, editC;
private double doubleA,doubleB,doubleC;
public Something(Activity a) {
click();
}
public void click(){
editA = (EditText) findViewById(R.id.editText);
editB = (EditText) findViewById(R.id.editText2);
editC = (EditText) findViewById(R.id.editText3);
doubleA =Double.parseDouble(editA.getText().toString());
doubleB =Double.parseDouble(editB.getText().toString());
add = (Button) findViewById(R.id.add);
subtract = (Button) findViewById(R.id.subtract);
multiply = (Button) findViewById(R.id.multiply);
devide = (Button) findViewById(R.id.devide);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
doubleC = doubleA+doubleB;
String s = "" + doubleC;
editC.setText(s);
}
});
subtract.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
doubleC = doubleA-doubleB;
String s = "" + doubleC;
editC.setText(s);
}
});
multiply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
doubleC = doubleA*doubleB;
String s = "" + doubleC;
editC.setText(s);
}
});
devide.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
doubleC = doubleA/doubleB;
String s = "" + doubleC;
editC.setText(s);
}
});
}
}
******************activity_main.xml****************
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/idk"
android:textSize="17sp"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="5"
android:id="#+id/editText"
android:hint="First number"
android:layout_centerVertical="true"
android:layout_alignLeft="#+id/textView"
android:layout_alignStart="#+id/textView" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="5"
android:id="#+id/editText2"
android:hint="Second number"
android:layout_centerVertical="true"
android:layout_alignRight="#+id/textView"
android:layout_alignEnd="#+id/textView" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add"
android:id="#+id/add"
android:layout_alignParentBottom="true"
android:layout_alignLeft="#+id/editText"
android:layout_alignStart="#+id/editText"
android:layout_marginBottom="166dp" />
<Button
android:layout_width="100dp"
android:layout_height="50dp"
android:text="Subtract"
android:id="#+id/subtract"
android:layout_alignTop="#+id/multiply"
android:layout_alignLeft="#+id/add"
android:layout_alignStart="#+id/add" />
<Button
android:layout_width="100dp"
android:layout_height="50dp"
android:text="Multiply"
android:id="#+id/multiply"
android:layout_marginTop="58dp"
android:layout_below="#+id/devide"
android:layout_alignRight="#+id/devide"
android:layout_alignEnd="#+id/devide" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Devide"
android:id="#+id/devide"
android:layout_below="#+id/editText"
android:layout_alignLeft="#+id/editText2"
android:layout_alignStart="#+id/editText2" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="20"
android:id="#+id/editText3"
android:layout_below="#+id/textView"
android:hint="Results"
android:layout_centerHorizontal="true"
android:layout_marginTop="62dp" />
</RelativeLayout>
The fact that you have created a constructor for the Something class
public Something(Activity a) {
click();
}
instead of using onCreate() is probably the source of the error.
Something is derived from Activity, in which you have to override onCreate() at the very least, and set the View of your Activity in it. You haven't done that, and instead you have created a constructor for Something which is also not allowed.
The solution to your problem is to replace the constructor with onCreate() and set the View of that Activity using setContentView(). Also, you cannot create an Activity object using
new Something(this);
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
}
});
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);
}