I ahve made a simple radioButton demo in android.In that i have put a radiogroup with two radio buttons named "male" and "female"...and a button .I want is when one of them pressed the name related to that particular radiobutton should be in toast.I have tried as below thats not working:
Activity.java
package com.example.radiobuttondemo;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.Toast;
public class MainActivity extends Activity {
RadioButton rd1,rd2;
Button b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rd1=(RadioButton)findViewById(R.id.radio0);
rd2=(RadioButton)findViewById(R.id.radio1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(rd1.isChecked()){
Toast.makeText(getApplicationContext(), "male", 0).show();
}
else{
Toast.makeText(getApplicationContext(), "Female", 0).show();
}
}
});
}
}
You forgot to initialize your Button b.
So when you're doing b.setOnClickListener, your program throws a NullPointerException and make your app closed.
You must bind your button with the Button object (that you named b) in your MainActivity class.
There is an action listener on b, but b is not binded...
Personally, I've always used RadioGroup for my radio buttons. If you didn't use that, how would it know to uncheck one radio button when you checked the other radio button?
See http://www.mkyong.com/android/android-radio-buttons-example/
Now if you're dealing with a normal checkbox, your approach would be fine I suppose. A normal checkbox wouldn't need to know about its siblings.
Do the check against RadioButton group itself:
switch (radioGroup.getCheckedRadioButtonId()) {
case rd1:
Toast.makeText(getApplicationContext(), "male", 0).show();
break;
case rd2:
Toast.makeText(getApplicationContext(), "Female", 0).show();
break;
)
Related
i am having issues getting the coding for onClick to work correctly i have a main activity that contains 8 buttons button 1 should open face book to a page 2,4,5,6 and 7 should open a web browser to defined page and button 8 to open phone dialer with preset number to call. I can not get this to work with out crashing the app i can set one onclick listener to button 1 and get it to work but when i add the next one it crashes the app i get no errors in eclipse i was told to do it with a fragment to handle the onclicks but im lost on how to do this can any one help me with this coding???
This is what i have so far just for 2 buttons still haven't got the one to open face book or the one to open phone dialer but this is as far as i get then it crashes – Jerry 33 mins ago
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addButtonClickListner();
}
public void addButtonClickListner() {
Button btnNavigator = (Button)findViewById(R.id.imageButton2);
btnNavigator.setOnClickListener(new OnClickListener(){
public void onClick(View arg) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("www.*****.com"));
startActivity(intent);
}
});
}
Do this instead
....
package com.example.testcode;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
// Test code: import android.widget.TextView;
// Let your class implement the OnClickListener interface directly. This
// will let you use the onClickListener
class MainActivity extends Activity implements OnClickListener{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// "find" our views by their id's in our activity's layout
Button button1 = (Button) findViewById(R.id.button1);
Button button2 = (Button) findViewById(R.id.button2);
//...... continue for button3 - button8
// set our "click" listeners for each of our buttons
button1.setOnClickListener(this);
button2.setOnClickListener(this);
//...... continue for button3 - button 8
}
// Because our class implements the OnClickListener interface
// it will be listening for "clicks". Because of this, we can
// override the click listener's default onClick(View v) method.
// View v is our view, or our button, that is "clicked".
#Override
public void onClick(View v) {
// Test code: TextView text = (TextView) findViewById(R.id.text);
// This is the statement that will allow each of your buttons
// to perform different processes. For my test code, I have each
// button reset the TextView I have displayed in the top of my
// layout.
switch(v.getId()){
case R.id.button1:
// Test code: text.setText("Button 1");
break;
case R.id.button2:
// Test code: text.setText("Button 2");
break;
//...... continue for button3 - button 8
default:
Log.d(getApplication().getPackageName(), "Button click error!");
break;
}
}
}
Please take a look at my comments. The portion that is commented as
// Test Code:
is code that is pretty much useless for what you are doing. The Test Code from the switch statement is what you need to replace with what you want to do with each individual button. It is also important to note that where I say "//...... continue for button3 - button8" I simply mean to repeat the pattern that I have started with the first two buttons with the remaining six.
If you would like to test it with my given test code, here is my layout (just make sure you erase "// Test Code: " so that the test code lines are no longer commented out:
<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=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Press a button"
android:id="#+id/text" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 1"
android:id="#+id/button1" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 2"
android:id="#+id/button2" />
</LinearLayout>
NOTES:
It is important to understand that in "good" xml layouts, the "android:text=" portion will be set to 'android:text=#string/"string_id"' instead of some general string to help with localization.
Make sure you change the very top line that declares the package to whatever package you have the Activity placed in. The name of this package is found at "Application"/src/"package_name" and is usually something like com.example.applicationname
I also want to say that I have included the comments in the code so that it can be copied and pasted without having to revisit this link over and over again in case anyone wants to use the code as a guide, not because I wanted tons of code posted in the answer.
Sometime onClick listener doesn't work because of some other
transparent view is on top of your view.
Well... here's a problem it looks like I'm not the first to experience looking through other questions, however I can't find one that's Android-specific (others are C++ or straight java with different scenarios).
I have a calculator that determines your fuel mileage needs with given user inputs. The thing I'm adding now is a "burnoff" aspect where you can calculate the weight lost over the course of the race. Before adding the weight/burnoff element, everything worked fine.
Now, everything calculates normally except the weight on the first click.
On the second click (and subsequent clicks) it calculates properly. I suspect it has something to do with the switch statement and its location, but I could be wrong.... and even if I'm not, I'm not sure how to change it.
Looking for help on getting it all functioning properly on the first click. Thanks!
EDIT: The non-exception Toast text I put in as a debugger to determine if it was a math issue or what in the code. It pops up with "0.0" on the first click, then either "6.2" or "6.6" on subsequent clicks.
package com.tomcat.performance;
import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;
public class Fuelsimple extends Activity implements OnCheckedChangeListener{
double fuelweight;
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
switch (checkedId){
case R.id.rbMethanol:
fuelweight = 6.6;
break;
case R.id.rbGasoline:
fuelweight = 6.2;
break;}
}
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.fuelsimple);
RadioGroup rgFuelType = ((RadioGroup) findViewById (R.id.rgFuelType));
rgFuelType.setOnCheckedChangeListener(this);
RadioButton rbMethanol = ((RadioButton) findViewById(R.id.rbMethanol));
RadioButton rbGasoline = ((RadioButton) findViewById(R.id.rbGasoline));
Button gen = ((Button) findViewById(R.id.submit));
gen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
EditText fuelUsed, pracLaps, featureLaps;
pracLaps = ((EditText) findViewById(R.id.pracLaps));
fuelUsed = ((EditText) findViewById(R.id.fuelUsed));
featureLaps = ((EditText) findViewById(R.id.featureLaps));
TextView textLPGValue, textFuelNeededValue, textBurnoffValue;
try{
double pracLapsVar = Double.parseDouble(pracLaps.getText().toString());
double fuelUsedVar = Double.parseDouble(fuelUsed.getText().toString());
double featureLapsVar = Double.parseDouble(featureLaps.getText().toString());
double efficiency = (pracLapsVar / fuelUsedVar);
double fuelNeeded = (featureLapsVar / efficiency);
double burnoff = (1.05 * (fuelNeeded * fuelweight));
Toast andJelly = Toast.makeText(Fuelsimple.this, String.valueOf(fuelweight), Toast.LENGTH_LONG);
andJelly.show();
textLPGValue = ((TextView) findViewById(R.id.textLPGValue));
textFuelNeededValue = ((TextView) findViewById(R.id.textFuelNeededValue));
textBurnoffValue = ((TextView) findViewById(R.id.textBurnoffValue));
textLPGValue.setText(String.valueOf(String.format("%.3f", efficiency)) + " laps per gallon");
textFuelNeededValue.setText(String.valueOf(String.format("%.3f", fuelNeeded)) + " gallons");
textBurnoffValue.setText(String.valueOf(String.format("%.2f", burnoff)) + " pounds");
} catch (NumberFormatException e) {Toast andEggs = Toast.makeText(Fuelsimple.this, "Please complete all fields and enter your fuel & lap info in decimals or whole numbers.", Toast.LENGTH_LONG); andEggs.show();}
catch (NullPointerException n) {Toast andEggs = Toast.makeText(Fuelsimple.this, "Please enter ALL lap and fuel data.", Toast.LENGTH_LONG);
andEggs.show();}
}}
);
}
public void onClick(View v) {
}
}
As far as I can tell, your variable fuelWeight is never initialized until a radio button is pressed. The simplest way to fix this would be to call setChecked(true) on either rbmethanol or rbGasoline after setting the listener, maybe right below where you initialize those variables. Doing it after setting the listener is important, because you want the switch statement to be resolved. Right now, before you press a radio button, fuelWeight, as with all numeric primitive data types, will be initialized to 0. This is probably the reason your first calculations are wrong.
You can also have a look at CheckChangeListener.It is called whenever the check state changes.
cbSave.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int visibility = isChecked ? View.VISIBLE : View.GONE;
findViewById(R.id.nameInstructions).setVisibility(visibility);
findViewById(R.id.name).setVisibility(visibility);
}
Below is my main activity file. I am stuck with the bottom area (commented out). I want to make it so that when I hit button b1, the text changes from what it is for default. So say it says "hello" by default, I want to switch the text to something like "how are you" when you press button b1. I have tried many things, but I always get errors. Can someone help me?
package com.wdmc85.donottouch;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class DoNotTouchActivity extends Activity
implements OnClickListener {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b1 = (Button) this.findViewById(R.id.b1);
b1.setOnClickListener(this);
}
#Override
public void onClick(View v)
{
switch(v.getId())
{
case R.id.b1:
//WHAT DO I PUT IN HERE?? I WANT IT SO WHEN YOU HIT BUTTON B1, THE
//TEXT CHANGES FROM WHAT IT IS FOR DEFAULT. SO SAY IT SAYS "HELLO"
//AS DEFAULT, HOW DO I MAKE IT SO WHEN YOU PRESS BUTTON B1 THE TEXT
//CHANGES FROM "HELLO" TO "HOW ARE YOU?" I HAVE TRIED ALL SORTS OF
//THINGS BUT NOTHING HAS WORKED
break;
}
}
}
if want to change text of the button itself
switch(v.getId())
{
case R.id.b1:
Button b1 = (Button) v;
b1.setText("HOW ARE YOU?");
break;
}
if want to change text of the any other Textview
switch(v.getId())
{
case R.id.b1:
TextView tv = (TextView ) this.findViewById(R.id.<tvid>);
tv .setText("HOW ARE YOU?");
break;
}
You should use below method to change text of text view.
textView.setText("your text");
reference link is >> textview>>setText()
can use same for button and other views.
hey I'm creating an app with two switches on it that change the background of the xml.
however, if the user touches button 1 then 2 I want it to change the background from pic1 to pic2(on first button hit) then pic4(on second button hit)
but if the user touches button 2 then 1 I want it to change the background from pic1 to pic3(on first button hit) then pic4(on second button hit)
at the moment this is my script;
package com.jamie.game;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class level2 extends Activity implements OnClickListener{
Button button1;
View targetView;
Button button2;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.level2);
targetView = (View)findViewById(R.id.level2);
button1 = (Button) findViewById(R.id.button1);
button1.setVisibility(View.VISIBLE);
button1.setBackgroundColor(Color.TRANSPARENT);
button1.setOnClickListener((android.view.View.OnClickListener)this);
button2 = (Button) findViewById(R.id.button2);
button2.setVisibility(View.VISIBLE);
button2.setBackgroundColor(Color.TRANSPARENT);
button2.setOnClickListener((android.view.View.OnClickListener)this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId()==(R.id.button1)){
targetView.setBackgroundResource(R.drawable.pic2);
if(v.getId()==(R.id.button2)){
targetView.setBackgroundResource(R.drawable.pic4);
}else
if(v.getId()==(R.id.button2)){
targetView.setBackgroundResource(R.drawable.pic3);
if(v.getId()==(R.id.button2)){
targetView.setBackgroundResource(R.drawable.pic4);
}
}
}
but all this does is alternate between pic2 and pic3 on button clicks
Probably you need to create a variable to store the ID of the button that was just clicked. Then, when you receive the next click, you can just check this variable to know if the sequence matches your condition. For example, if you click the first button - store its ID in an int lastChecked variable, then when you click the second button - you should whether lastChecked equals to the first button ID. If it is - then you can run your View changing code. Hope this helps.
I want to program a function that the toast exist when there is nothing
in the "edittext" box (id / password), but it dosen't work.
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.content.Intent;
import android.widget.EditText;
import android.widget.Toast;
import android.view.View.OnClickListener;
import android.text.Editable;
public class Test extends Activity
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button1 = (Button) findViewById(R.id.button1);
EditText id = (EditText) findViewById(R.id.id);
EditText pwd = (EditText) findViewById(R.id.pwd);
Editable Str_id;
Editable Str_pwd;
Str_id = id.getText();
Str_pwd = pwd.getText();
button1.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v){
if(Str_id==null || Str_pwd == null){
Toast.makeText(Test.this, "Please Enter User ID / Password", Toast.LENGTH_LONG).show();
}
});
}
}
move the following lines inside onClick and try:
Str_id = id.getText();
Str_pwd = pwd.getText();
EDIT: Move
Editable Str_id;
Editable Str_pwd;
Str_id = id.getText();
Str_pwd = pwd.getText();
inside onClick().
I do not recommend toasting a message that a field is required. You're better off just giving the EditText focus, this focus tells the user that this field is required. Its less information on the screen and its subtle, which is important. You don't want to disturb the user too much.
The idea is...
When the submit button is clicked, check the EditTexts if any of them are empty, notify the user through requesting focus, also make sure your UI tells them before hand that the fields required. The hint of the EditText works well for this.