Can we create a centralized event handler for multiple buttons in Android?
If so, how can we do that?
Yonatan Nir's solution is the easiest but if you're already using Butterknife you can do it like this:
#OnClick({ R.id.button1, R.id.button2, R.id.button3})
public void onButtonClicked(View theViewThatIsClicked) {
Toast.makeText(this, "Clicked!", LENGTH_SHORT).show();
}
You can do it by using the View parameter you are given:
#Override
public void onClick(final View v)
{
switch (v.getId())
{
case R.id.Button1: ....
case R.id.Button2: ...
}
}
For example:
class MyActivity extends Activity implements View.OnClickListener
{
#Override
public void onCreate(final Bundle savedInstanceState)
{
Button button1 = (Button)findViewById(R.id.Button1);
Button button2 = (Button)findViewById(R.id.Button2);
button1 .setOnClickListener(this);
button2 .setOnClickListener(this);
}
#Override
public void onClick(final View v)
{
switch (v.getId())
{
case R.id.Button1: ....
case R.id.Button2: ...
}
}
}
Here is a pseudo code for this:
class FooActivity extends Activity implements View.OnClickListener{
//inside onCreate(), find buttons with their ids, For ex;
Button btn1 = (Button)findViewById(R.id.btn1);
Buttn btn2 = (Button)findViewById(R.id.btn2)
// and register listeners for appropriate Buttons
btn1.setOnClickListener(this);
btn2.setOnClickListener(this)
//then implement the listener interface method
#Override
public void onClick(View v){
int id = v.getId();
if(id == R.id.btn1 || id==R.id.btn2){
doSameForBothButtons();
}
}
}
}
Here is how I centralize my Click handlers.
Note: It's useful for different types of Views as well, not only Buttons.
Even mixed types (i.e.: you can handle an ImageButton, a TextView and a Button using the same method for all).
Example layout (note the android:onClick="clickHandler" attribute on each Button):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f000"
>
<Button
android:id="#+id/Button1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textStyle="bold"
android:text="1"
android:onClick="clickHandler"
/>
<Button
android:id="#+id/Button2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textStyle="bold"
android:text="2"
android:onClick="clickHandler"
/>
<Button
android:id="#+id/Button3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textStyle="bold"
android:text="3"
android:onClick="clickHandler"
/>
</LinearLayout>
Accompanying code (note the clickHandler method):
package com.dergolem.abc_2;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.Toast;
public class MultiClick
extends Activity
{
Button btn1 = null;
Button btn2 = null;
Button btn3 = null;
#Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.multi_click);
btn1 = (Button) findViewById(R.id.Button1);
btn2 = (Button) findViewById(R.id.Button2);
btn3 = (Button) findViewById(R.id.Button3);
}
public void clickHandler(final View v)
{
String str = "";
switch (v.getId())
{
case R.id.Button1:
{
str = "1";
break;
}
case R.id.Button2:
{
str = "2";
break;
}
case R.id.Button3:
{
str = "3";
break;
}
}
Toast.makeText(this, "Button " + str, Toast.LENGTH_SHORT).show();
}
}
Related
I am using Android Studio
I'm wanting to change the color of my button, with each click.
To cycle it through around 10 colors and start over again in a continuous loop.
For example I'm using setBackgroundResource(#drawable/oval)
oval = blue circle button
oval2 = red circle button
oval3 = green circle button and so on.
So far I have it that button1 starts as oval(blue) and onClick turns into oval2(red)
So my question is, how to add another click to change it to oval3(green) and then cycle it back to the start oval(blue)?
MainActivity.java
package com.example.shadowz.buttononclick;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.support.v4.app.Fragment;
import android.support.v4.view.TintableBackgroundView;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity
{
private Button colorChangeButton;
private TextView basicText;
private RelativeLayout background;
Button button1;
Button button2;
Button button3;
Button button4;
Button button5;
Drawable oval1;
Drawable oval2;
Drawable oval3;
Drawable oval4;
Drawable oval5;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
background = (RelativeLayout) findViewById(R.id.backgroundLayout);
basicText = (TextView) findViewById(R.id.button1);
colorChangeButton = (Button) findViewById(R.id.button1);
// Code Break
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button3 = (Button) findViewById(R.id.button3);
button4 = (Button) findViewById(R.id.button4);
button5 = (Button) findViewById(R.id.button5);
// Code Break
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v == button1) {
button1.setBackgroundResource(R.drawable.oval2);
}
}
});
// Code Break
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v == button2) {
button2.setBackgroundResource(R.drawable.oval3);
}
}
});
// Code Break
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v == button3) {
button3.setBackgroundResource(R.drawable.oval4);
}
}
});
// Code Break
button4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v == button4) {
button4.setBackgroundResource(R.drawable.oval5);
}
}
});
// Code Break
button5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v == button5) {
button5.setBackgroundResource(R.drawable.oval6);
}
}
});
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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="com.example.shadowz.buttononclick.MainActivity"
android:id="#+id/backgroundLayout">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
<Button
android:id="#+id/button1"
android:layout_width="140dp"
android:layout_height="140dp"
android:text="button1"
android:background="#drawable/oval"
android:padding="#dimen/abc_action_bar_content_inset_material"
android:layout_below="#+id/button3"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:id="#+id/button2"
android:layout_width="140dp"
android:layout_height="140dp"
android:text="button2"
android:background="#drawable/oval"
android:layout_alignTop="#+id/button1"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:id="#+id/button3"
android:layout_width="140dp"
android:layout_height="140dp"
android:text="button3"
android:background="#drawable/oval"
android:singleLine="false"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:id="#+id/button4"
android:layout_width="140dp"
android:layout_height="140dp"
android:text="button4"
android:background="#drawable/oval"
android:padding="#dimen/abc_action_bar_content_inset_material"
android:layout_above="#+id/button2"
android:layout_alignLeft="#+id/button2"
android:layout_alignStart="#+id/button2" />
<Button
android:id="#+id/button5"
android:layout_width="140dp"
android:layout_height="140dp"
android:text="button5"
android:background="#drawable/oval"
android:padding="#dimen/abc_action_bar_content_inset_material"
android:layout_alignBottom="#+id/button1"
android:layout_centerHorizontal="true"
android:layout_marginBottom="78dp" />
</RelativeLayout>
You can do this by following:
Create integer-array in resources:
<integer-array name="backgrounds">
<item>#drawable/oval1</item>
<item>#drawable/oval2</item>
<item>#drawable/oval3</item>
<item>#drawable/oval4</item>
<item>#drawable/oval5</item>
</integer-array>
Then create special OnClickListener class inside your class code
private static class MyClickListener implements View.OnClickListener {
private int mBackgroundIndex = 0;
private final TypedArray mBackgrounds;
public MyClickListener(Context context) {
mBackgrounds = context.getResources().obtainTypedArray(R.array.backgrounds);
}
#Override
public void onClick(View v) {
mBackgroundIndex++;
if (mBackgroundIndex >= mBackgrounds.length()) {
mBackgroundIndex = 0;
}
v.setBackgroundResource(mBackgrounds.getResourceId(mBackgroundIndex, 0));
}
#Override
protected void finalize() throws Throwable {
mBackgrounds.recycle();
super.finalize();
}
}
And then set that listener to each button:
button1.setOnClickListener(new MyClickListener(this));
button2.setOnClickListener(new MyClickListener(this));
button3.setOnClickListener(new MyClickListener(this));
button4.setOnClickListener(new MyClickListener(this));
button5.setOnClickListener(new MyClickListener(this));
This should result in the following MainActivity code:
package com.example.shadowz.buttononclick;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.support.v4.app.Fragment;
import android.support.v4.view.TintableBackgroundView;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private Button colorChangeButton;
private TextView basicText;
private RelativeLayout background;
Button button1;
Button button2;
Button button3;
Button button4;
Button button5;
Drawable oval1;
Drawable oval2;
Drawable oval3;
Drawable oval4;
Drawable oval5;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
background = (RelativeLayout) findViewById(R.id.backgroundLayout);
basicText = (TextView) findViewById(R.id.button1);
colorChangeButton = (Button) findViewById(R.id.button1);
// Code Break
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button3 = (Button) findViewById(R.id.button3);
button4 = (Button) findViewById(R.id.button4);
button5 = (Button) findViewById(R.id.button5);
button1.setOnClickListener(new MyClickListener(this));
button2.setOnClickListener(new MyClickListener(this));
button3.setOnClickListener(new MyClickListener(this));
button4.setOnClickListener(new MyClickListener(this));
button5.setOnClickListener(new MyClickListener(this));
}
private static class MyClickListener implements View.OnClickListener {
private int mBackgroundIndex = 0;
private final TypedArray mBackgrounds;
public MyClickListener(Context context) {
mBackgrounds = context.getResources().obtainTypedArray(R.array.backgrounds);
}
#Override
public void onClick(View v) {
mBackgroundIndex++;
if (mBackgroundIndex >= mBackgrounds.length()) {
mBackgroundIndex = 0;
}
v.setBackgroundResource(mBackgrounds.getResourceId(mBackgroundIndex, 0));
}
#Override
protected void finalize() throws Throwable {
mBackgrounds.recycle();
super.finalize();
}
}
}
i've created an android application which displays a number picker, it all works fine...but the problem is with the design....when i run the application in gingerbread the number picker looks fine good....but when i run the same stuff in ice-cream sandwich and jelly bean the number picker design is been altered just like as shown below.
can anyone please tell me how to retain the default number-picker design that is in gingerbread in jelly bean
when runs in ice-cream sandwich and jelly bean
when runs in ginger-bread
i'm using a custom dialog box within which the number picker is placed, the code is as given below
import android.app.Activity;
import android.app.Dialog;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.NumberPicker;
public class QuantityChangeDialog extends Dialog implements android.view.View.OnClickListener {
public Activity c;
public Dialog d;
public Button save, cancel;
NumberPicker np;
public QuantityChangeDialog(Activity a) {
super(a);
// TODO Auto-generated constructor stub
this.c = a;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
setContentView(R.layout.selecteditem_dialog);
save = (Button) findViewById(R.id.btn_save);
cancel = (Button) findViewById(R.id.btn_cancel);
save.setOnClickListener(this);
cancel.setOnClickListener(this);
np = (NumberPicker) findViewById(R.id.qntypicker);
np.setMaxValue(120);
np.setMinValue(1);
np.setValue(3);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_save:
c.finish();
break;
case R.id.btn_cancel:
dismiss();
break;
default:
break;
}
dismiss();
}
}
Quoting from docs
If the current theme is derived from Theme the widget presents the current value as an editable input field with an increment button above and a decrement button below. Long pressing the buttons allows for a quick change of the current value. Tapping on the input field allows to type in a desired value.
You need to set your theme that is derieved from Theme like fro example Theme.NoTitleBar.Fullscreen
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: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" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
<Button
android:id="#+id/button11"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Open" />
</RelativeLayout>
dialog.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:theme = "#style/cust_dialog"
android:layout_height="fill_parent" >
<NumberPicker
android:id="#+id/numberPicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="64dp" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/numberPicker1"
android:layout_marginLeft="20dp"
android:layout_marginTop="98dp"
android:layout_toRightOf="#+id/numberPicker1"
android:text="Cancel" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/button2"
android:layout_alignBottom="#+id/button2"
android:layout_marginRight="16dp"
android:layout_toLeftOf="#+id/numberPicker1"
android:text="Set" />
</RelativeLayout>
Then to display custom dialog
public class MainActivity extends Activity implements NumberPicker.OnValueChangeListener
{
private TextView tv;
static Dialog d ;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.textView1);
tv.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
tv.setTextColor(Color.RED);
}
else if (event.getAction() == MotionEvent.ACTION_UP) {
// set to normal color
tv.setTextColor(0);
}
return true;
}
});
Button b = (Button) findViewById(R.id.button11);
b.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
show();
}
});
}
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
Log.i("value is",""+newVal);
}
public void show()
{
final Dialog d=new Dialog(this,R.style.cust_dialog);
d.setTitle("NumberPicker");
d.setContentView(R.layout.dialog);
Button b1 = (Button) d.findViewById(R.id.button1);
Button b2 = (Button) d.findViewById(R.id.button2);
final NumberPicker np = (NumberPicker) d.findViewById(R.id.numberPicker1);
np.setMaxValue(100);
np.setMinValue(0);
np.setWrapSelectorWheel(false);
np.setOnValueChangedListener(this);
b1.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
tv.setText(String.valueOf(np.getValue()));
d.dismiss();
}
});
b2.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
d.dismiss();
}
});
d.show();
}
}
Styles.xml
</style>
<style name="cust_dialog" parent="#android:style/Theme.NoTitleBar.Fullscreen">
</style>
Snap Shot
You can just add this attribute into your NumberPicker
android:theme="#android:style/Theme.Dialog"
E.g.
<NumberPicker android:theme="#android:style/Theme.Dialog"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
This will limit the impact to just the number picker widget, not the entire activity page.
I have 5 buttons every one has letter (Button "H",Button "E"Button "L"Button "L"Button "O") which make the word "HELLO". what I need is to make on click sequence to these buttons so if I click "H" first and "E" second until complete the word the app will do something, But if I click "L" first will give me some error message.
Any Idea to do this sequence?
Thanks
Just have an Array like this:
int[] tracker = new int[5];
and when you click a button, say "H", set tracker[0] = 1;
but when you click a button, say "L", check whether all the previous button values are 1. If yes, then set the corresponding tracker to 1 else, show an error message, and do not make any change to the tracker Array.
Something Like this:
onHClick{
tracker[0] = 1;
}
onEClick{
for(int i=0; i<1; i++){
if(tracker[i] == 0){
//show error message and return;
}else{
tracker[1] = 1;
return;
}
}
}
You can do something like
When activity started you just make other button Enabled = false of something like that. But make the first button Enabled. Don't make the Visible=false.
Now on click of Button "H" make enable Button "E" and so on.
So user will only have to click the button in sequence. Button can not be presses in any random manner.
Try this and let me know that it works or not.
Very Interesting and exactly same to your requirement..check once..
If you give any string other than HELLO also works better.
public class ButtonTest extends Activity
{
private String result="";
String sampleText = "HELLO";
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
int noOfBtns = sampleText.length();
LinearLayout ll = (LinearLayout)findViewById(R.id.btnlay);
final TextView tvtext = (TextView)findViewById(R.id.result);
final Button[] btns = new Button[noOfBtns];
for(int i=0;i<noOfBtns;i++)
{
btns[i] = new Button(this);
btns[i].setText(sampleText.substring(i,i+1));
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
ll.addView(btns[i], lp);
final int j = i;
btns[i].setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
System.out.println(j+" "+result.length());
if(j == result.length())
{
result = result+btns[j].getText().toString();
if(sampleText.startsWith(result))
{
tvtext.setText(result);
}
}
else
{
Toast.makeText(getApplicationContext(), "Wrong Button Pressed", Toast.LENGTH_SHORT).show();
}
}
});
}
}
}
Layout file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/result"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:textColor="#fff"/>
<LinearLayout
android:id="#+id/btnlay"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
</LinearLayout>
</LinearLayout>
Try the following
package com.example.buttonsequence;
import java.util.ArrayList;
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.TextView;
import android.widget.Toast;
public class MainActivity extends Activity
{
ArrayList<Button> buttonList=null;
TextView resultTextView=null;
Button buttons[]=null;
String helloStr="HELLO";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonList=new ArrayList<Button>();
buttons=new Button[5];
this.resultTextView=(TextView) this.findViewById(R.id.result_text);
this.resultTextView.setText("");
buttons[0]=(Button)this.findViewById(R.id.h_button);
buttons[1]=(Button)this.findViewById(R.id.e_button);
buttons[2]=(Button)this.findViewById(R.id.l_button);
buttons[3]=(Button)this.findViewById(R.id.l2_button);
buttons[4]=(Button)this.findViewById(R.id.o_button);
for(int k=0;k<5;k++)
buttons[k].setOnClickListener(onClickListener);
Button button=(Button)this.findViewById(R.id.exit_button);
button.setOnClickListener
(
new OnClickListener()
{
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
finish();
}
}
);
}
OnClickListener onClickListener=new OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
Button b=(Button)v;
buttonList.add(b);
int size=buttonList.size();
if(size>0)
{
StringBuilder resultBuilder=new StringBuilder();
for(int i=0;i<size;i++)
{
Button tempButton=buttonList.get(i);
if(tempButton==buttons[i])
{
resultBuilder.append(helloStr.charAt(i));
if(i==4)
{
resultTextView.setText(resultBuilder.toString()+" clicked");
buttonList.clear();
}
else
{
resultTextView.setText(resultBuilder.toString()+" clicked");
}
}
else
{
buttonList.remove(i);
Toast.makeText(getApplicationContext(), "No correctly clicked", Toast.LENGTH_SHORT).show();
break;
}
}
}
else
{
resultTextView.setText("Invalid pressed");
}
}
};
}
activity_main.xml
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
<Button
android:id="#+id/h_button"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="H" />
<Button
android:id="#+id/e_button"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="E" />
<Button
android:id="#+id/l_button"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="L" />
<Button
android:id="#+id/l2_button"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="L" />
<Button
android:id="#+id/o_button"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="O" />
<TextView
android:id="#+id/result_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Small Text"
android:textAppearance="?android:attr/textAppearanceSmall" />
<Button
android:id="#+id/exit_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Exit" />
</LinearLayout>
I don't know exactly your flow but you can try this.
set Tag to each button as its Text, like this.
b.setTag("H");
and than after like this.
Button b;
String name = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String s = (String) v.getTag();
name +=s;
if( "HELLO".startsWith(name)){
<VALID>
}else{
<ERROR>
}
}
});
}
check the variable name on each button click with your original word i.e. HELLO like above.
I have a problem with my android project. I cannot get access to my button. I have attach my class code==http://pastebin.com/A5ZTBkhd. Please anyone help me.
Here is my code -
package com.droid.androiddoctor;
import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
public class AndroidDoctorMainActivity extends Activity implements OnClickListener{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_android_doctor_main);
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_android_doctor_main, menu);
return true;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId())
{
case R.id.btnSubmit:
String e="hello";
String error = e.toString();
Dialog d = new Dialog(this);
d.setTitle("Dang it!");
TextView tv = new TextView(this);
tv.setText(error);
d.setContentView(tv);
d.show();
break;
}
}
}
.Here is my code.when i push submit nothing happens. and the xml file is====
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/btnSubmit"
androi:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Submit" />
<Button
android:id="#+id/btnExit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Exit" />
</LinearLayout>
You did not set the listener for your widgets at all. Try this:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_android_doctor_main);
Button button1 = (Button) findViewById(R.id.btnSubmit);
button1.setOnClickListener(this)
}
I would suggest you to go through Android's UI Guide.
I wouldn't implement OnClickListener like that, try to add it like this in your class:
public class AndroidDoctorMainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_android_doctor_main);
Button button1 = (Button) findViewById(R.id.btnSubmit);
Button button2 = (Button) findViewById(R.id.btnExit);
button1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//your code for click on this button
}});
button2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//your code for this button
//or if you just want to exit from activity, just call:
finish();
}});
#Override
public boolean onCreateOptionsMenu(Menu menu) {
}
}
My View
<Button android:id="#+id/button1" android:text="Text 1"
android:layout_height="wrap_content"
android:layout_width="fill_parent"></Button>
<Button android:id="#+id/button2" android:text="Text 2"
android:layout_height="wrap_content"
android:layout_width="fill_parent"></Button>
<Button android:id="#+id/button3" android:text="Text 3"
android:layout_height="wrap_content"
android:layout_width="fill_parent"></Button>
<Button android:id="#+id/button4" android:text="Text 4"
android:layout_height="wrap_content"
android:layout_width="fill_parent"></Button>
I have an undefined amount of buttons and need get you text in a touch event.
How i do it?
Tnks a lot.
EDIT:
Thanks for all, this is result of the your Answers => https://play.google.com/store/apps/details?id=br.com.redrails.torpedos
My App :D
If you name all of your buttons "button1, button2, button3..." you can do this:
for(int i = 1; i <= buttonCount; i++) {
int id = getResources().getIdentifier("button" + i, "id", getPackageName() );
findViewById(id).setOnClickListener(this);
}
Where buttonCount is the amount of buttons you have. This method would be placed in onCreate().
Then for your onClick:
public void onClick(View v) {
if (v instanceof TextView) {
CharSequence text = ((TextView) v).getText();
// Do fun stuff with text
}
}
Your Activity will need to implement OnClickListener
You can get the text of a button by using the getText() method.
You can do :
Button button4= (Button) findViewById(R.id.button4);
text = button4.getText();
Here is a complete example:
import android.os.Bundle;
import android.widget.Toast;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;
public class MainActivity extends Activity implements OnClickListener
{
private Button btn1, btn2, btn3, btn4; // You can add more if you like
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn1 = (Button) findViewByID(R.id.button1);
btn2 = (Button) findViewByID(R.id.button2);
btn3 = (Button) findViewByID(R.id.button3);
btn4 = (Button) findViewByID(R.id.button4);
// declare the other buttons if any
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
btn3.setOnClickListener(this);
btn4.setOnClickListener(this);
// register the other buttons as well if any
}
#Override
public void onClick(View v)
{
String text = ((Button) v).getText();
Toast.makeText(this, "You clicked " + text , Toast.LENGTH_SHORT).show();
}
}