How to give an argument to a function using android xml? - android

I have an app with a lot of buttons (more than 300)
i want to know if there is a way to use android:onClick="function" with an arguments in my layout xml
because im too lazy to make a function for each button, and i want to do somenthin like
public void allbuttons(View view, String stringa) {
if stringa = 1 { bla bla bla}
elif stringa = 2 { blachos}
}
you get the idea

Give an id to each of your button.
In your common handler, just check the ((Button)view).getId() for the id in a switch (with the latest adk, you have to use if-else) and handle it differently in each case.
public class MyButtonClickHandler implements View.OnClickListener {
#Override
public void onClick(View v) {
Button button = (Button) v;
if (button.getId() == R.id.button1) {
Toast.makeText(Sample1Activity.this, "Toast1", 1000).show();
} else if (button.getId() == R.id.button2) {
Toast.makeText(Sample1Activity.this, "Toast2", 1000).show();
}
}
}
and in your onCreate of activities you can add
Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new MyButtonClickHandler());
I am adding function reference in the code but you can do it in xml file too.

Related

android multiply button case switch

I have been looking at some posts and still I cannot get mine code to work (I am a beginner) .. I am just tring to use the toast with my two buttons with a case switch .. When compiling it just crashes .. one something has an idea ?
Code :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
TextView et = (TextView) findViewById(R.id.txtHeader);
Button btnAdd = (Button) findViewById(R.id.btnAdd);
Button btnDis = (Button) findViewById(R.id.btnDisplay);
btnAdd.setOnClickListener((OnClickListener) this);
btnDis.setOnClickListener((OnClickListener) this);
}
public void OnClick(View v) {
switch (v.getId()) {
case R.id.btnAdd:
// Toast msg = Toast.makeText(getBaseContext(), "Torben", Toast.LENGTH_LONG);
// msg.show();
break;
case R.id.btnDisplay:
// Toast msg1 = Toast.makeText(getBaseContext(), "Henriksen", Toast.LENGTH_LONG);
// msg1.show();
break;
default:
break;
}
}
I see two main problems:
((OnClickListener) this
Make sure your class implements OnClickListener because you never need to cast if you are actually implementing the interface.'
The declaration of the class should be something like:
public class MyActivity extends Activity implements OnClickListener
Then change OnClick to lowercase o.
#Override
public void onClick(View v) {
some log output would be helpful!
a wild guess is that your activiy does not implement OnClickListener, why else would you cast this to OnClickListener?
just check in your layout manifest that whether the buttons id are correct and given the same id which your are using and if it is then please update the question with the LogCat output.
And also check that the activity is defined in manifest because there is no mistake in your code to implemts the onclick listener for multiple buttons.
Enjoy!!
Example adding a button listener:
Button b = ((Button)findViewById(R.id.button_name));
b.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
//do something
}
});
and make sure the button is defined in your xml file with the id #+id/button_name or #id/button_name (just make sure they match)

android view id is not correct

I create a whole layout setup in XML then attempt to attach listeners to the buttons using findViewById(). The problem I am having now is that the View parameter I receive in the method does not contain the ID of the view I clicked: 830009633920 vs 2131099657.
Button btnNext = (Button)findViewById(R.id.btnNext);
btnNext.setOnClickListener(this);
#Override
public void onClick(View view) {
if (view.getId() == R.id.btnNext) {
...
}
}
How about this:
Button btnNext = (Button)findViewById(R.id.btnNext);
btnNext.setOnClickListener(this);
#Override
public void onClick(View view)
{
switch (view.getId())
{
case R.id.btnNext:
...
break;
case R.id.foo:
...
break;
}
}
That should be working, so my only guess without seeing the rest of the code or layout is that you have set click handlers on two items that overlap.
If you plan on making an Android Library project switch like this will not work due to a recent change in the tool chain.
http://tools.android.com/tips/non-constant-fields
In general I find it is much simpler to use an anonymous class the handle clicks rather than a large single handler.
btnNext.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View view)
{
...
}
});
You might try this approach just to debug that the item you expect to get the click is what you are pressing, to make sure you don't have layout issues.
Try skipping the IDs, and just compare the actually view object. so something like this:
#Override
public void onClick(View view) {
if (view.equals(btnNext)) {
...
}
}

Button click to change background image of clicked button

I am trying to change the background image of a button that is clicked. The button whose image I am trying to toggle is the same button that is clicked. I ultimately want the program to test the current background image and change it to the other picture given the result of the test.
final Button testButton = (Button) findViewById(R.id.buttonTestButton);
testButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//toggle picture
if (testButton.equals(getResources().getDrawable(R.drawable.fakepicture))) {
testButton.setBackgroundResource(R.drawable.alternatepicture);
}
else {
testButton.setBackgroundResource(R.drawable.fakpicture);
}
}//end void onClick
});//end test button on click listener
try
testButton.getBackground().equals(getResources().getDrawable(R.drawable.fakepicture));
However ToggleButton might suit your case better.
As others have said, your equals method is comparing the button itself with the image, but you need to compare the background drawables.
I recommend loading the images drawables you want to use and then using their references later to make things more clear, something like this:
final Drawable first = getResources().getDrawable(
android.R.drawable.arrow_up_float);
final Drawable second = getResources().getDrawable(
android.R.drawable.arrow_down_float);
final Button testButton = (Button) findViewById(R.id.toggleButton);
testButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (testButton.getBackground().equals(first)) {
testButton.setBackgroundDrawable(second);
} else {
testButton.setBackgroundDrawable(first);
}
}
});
as the other friends answered , it is preferable to use the ToggleButton in Android ,
and in your case, if you want to keep your code , so your method should be like this :
final Button testButton = (Button) findViewById(R.id.buttonTestButton);
int status = 0;//GLOBAL VARIABLE : the status of the Button ( 0 or 1 )
testButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//toggle picture
if (status == 0) {
testButton.setBackgroundResource(R.drawable.alternatepicture);
status=1 ; // change the status to 1 so the at the second clic , the else will be executed
}
else {
testButton.setBackgroundResource(R.drawable.fakpicture);
status =0;//change the status to 0 so the at the second clic , the if will be executed
}
}//end void onClick
});//end test button on click listener
You can simply use ToggleButton: Android ToggleButton and use StateList for the changing of the background: StateList using the check attribute.
You can use Buttons or Image buttons..
private ImageButton mod1,mod2;
mod1 = (ImageButton) findViewById(R.id.mod1);
mod2 = (ImageButton) findViewById(R.id.mod2);
mod1.setOnClickListener(this);
mod2.setOnClickListener(this);
public void onClick(View v) {
mod1.getDrawable().clearColorFilter();
mod2.getDrawable().clearColorFilter();
switch (v.getId()) {
case R.id.mod1:
mod1.getDrawable().setColorFilter(0xfff47521,PorterDuff.Mode.SRC_ATOP);
break;
case R.id.mod2:
mod2.getDrawable().setColorFilter(0xfff47521,PorterDuff.Mode.SRC_ATOP);
break;
}
}

ParseInt Exception

I am creating a small calc app with EditText views and Im running into an runtime exception when the user leaves an EditText view empty causing the ParseInt to try and Parse nothing. Ive read that I need to 'Try' and 'Catch' this error before it occurs, but Im unsure of where and how to do this!
Any advice is much appreciated!
Here is my code:
public class HandlerExamples 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 button = (Button)findViewById(R.id.testButton);
button.setOnClickListener(this);
public void onClick(View v) {
String a,b,t;
double vis;
EditText txtbox1 = (EditText)findViewById(R.id.A);
EditText txtbox2 = (EditText)findViewById(R.id.B);
EditText txtbox3 = (EditText)findViewById(R.id.t);
TextView tv = (TextView) findViewById(R.id.Answer);
a = txtbox1.getText().toString();
b = txtbox2.getText().toString();
t = txtbox3.getText().toString();
vis = ((Integer.parseInt(a)*1) + (Integer.parseInt(b)*2)) / (Double.parseDouble(t));
tv.setText(double.toString(vis));
}
}
Thanks so much!
public void onClick(View v) {
int id = v.getId();
switch(id){
case R.id.xx:
//do things xx click
break;
case R.id.yy:
//do things yy click
break;
}
}
you can get the view id to know whick widget was clicked.
Changwei Yao defined one way you can do this, but here's the way most Android programmers would do this (programmatically), since it's a little easier to read and figure out what your widgets are doing:
But first, remove the implements OnClickListener from your Activity, as it's not needed.
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// what you want your button to do when clicked
}
}
editText.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// what you want your EditText to do when clicked
// (such as editText.setText(""))
}
}
Another way to do the same thing is to define android:onClick="insert_method_name_here" for the widgets that you want perform an action when clicked. In your case, in your main.xml (since that's what you're using in your Activity), you could write something like...
<Button android:id="#+id/testButton"
(other attributes you wish to apply to the button)
android:onClick="buttonAction" />
<EditText
(other attributes)
android:onClick="textAction" />
And then, in your Activity, you define the methods buttonAction(View v) and textAction(View v). Note that these methods must be public void, and must take the sole argument View v.
(One advantage of the XML method is that you don't necessarily have to define an android:id attribute for these widgets, unless you need to be able to manipulate them or extract information from them in your code (which means you will need to define an android:id for your EditText since you'll likely want the user's input))
If you only need to exclude the empty text field then hotveryspicy's solution is probably the quickest. For a secure solution: catching the NumberFormatException will filter anything that can not be converted to an integer.
int vis;
try {
vis = Integer.parseInt(a);
}
catch(NumberFormatException nfe) {
Log.e(TAG,"trying to convert:"+a+" to integer failed");
vis = 0;
}

Variable OnClick Listener Android

Is there a way to have 1 onClick Lister for many buttons where I can toss a case statement to do things based on what buttons were clicked.
I know I can make 100 different listeners for 100 buttons but I have to think I can create some nifty variables to do it in less lines of code.
Button btn1, btn2;
public void onCreate(Bundle b)
{
// here you do normal things like assigning a
// content view to the activity, initiate buttons, etc.
// then you assign the same listener to both buttons
btn1.setOnClickListener(yourListener);
btn2.setOnClickListener(yourListener);
}
// declare a OnClickListener that will execute different actions
// depending on the view that was clicked
View.OnClickListener yourListener = new View.OnClickListener(){
public void onClick (View v){
if( v == btn1 ){
// do something
}
elseif( v == btn1 ){
// do another thing
}
}
};
If you are using 1.6+ version of the SDK you can use android:onClick to set the onClick handler of a view. In your activity you must have a method with the following signature. The view is the view that was clicked.
void onClick(View v) {
switch(v.getId()) {
case R.id.button1:
//do something fantastic;
break;
}
}
public class MainActivity extends Activity implements View.OnClickListener{
btnXXX.setOnClickListener(this);
public void onClick(View v) {
if (v.getId()==R.id.btnXXX){
dialog.show();
} else {
handleOtherViews(v);
}
}
Alternatively, you can specify the method to call in xml:
<Button android:id="#id/button" android:text="#string/button" android:onClick="someMethod" />

Categories

Resources