Android which button index from array was pressed - android

How do I set up a OnClickListener to simply tell me which index button was pressed from an array of buttons. I can change text and color of these buttons using the array. I set them up like this.
TButton[1] = (Button)findViewById(R.id.Button01);
TButton[2] = (Button)findViewById(R.id.Button02);
TButton[3] = (Button)findViewById(R.id.Button03);
up to 36.

The OnClickListener is going to receive the button itself, such as R.id.Button01. It's not going to give you back your array index, as it knows nothing about how you have references to all the buttons stored in an array.
You could just use the button that is passed into your onClickListener directly, with no extra lookups in your array needed. Such as:
void onClick(View v)
{
Button clickedButton = (Button) v;
// do what I need to do when a button is clicked here...
switch (clickedButton.getId())
{
case R.id.Button01:
// do something
break;
case R.id.Button01:
// do something
break;
}
}
If you are really set on finding the array index of the button that was clicked, then you could do something like:
void onClick(View v)
{
int index = 0;
for (int i = 0; i < buttonArray.length; i++)
{
if (buttonArray[i].getId() == v.getId())
{
index = i;
break;
}
}
// index is now the array index of the button that was clicked
}
But that really seems like the most inefficient way of going about this. Perhaps if you gave more information about what you are trying to accomplish in your OnClickListener I could give you more help.

You can set Tag value and get the Tag on Click:
TButton[1] = (Button)findViewById(R.id.Button01);
TButton[1].setTag(1);
onClick(View v)
{
if(((Integer)v.getTag())==1)
{
//do something
}
}

Related

Numbered Checkboxes in Android

I want the user to be able to rank a list of fruits in the order that they like to most.
Say for example, consider the list as "Mango, Apple, Banana, Pineapple".
If they like Apple, Mango, Pineapple, Banana in this order I want to use checkboxes that show the rank when the user clicks on them.
Is this possible?
Thanks
Why don't you try with a counter. It start's at 0, when user press a checkbox you just add 1 to it and you have an array for each checkbox where you will save the number pressed.
You have final int[] fruits = new int[4]; and final int counter = 0;
public void onCheckboxClicked(View view) {
// Is the view now checked?
boolean checked = ((CheckBox) view).isChecked();
// Check which checkbox was clicked
switch(view.getId()) {
case R.id.checkbox_mango:
if (checked) {
counter++;
fruits[0] = counter;
} else {
counter--;
fruits[0] = 0;
}
break;
case R.id.checkbox_apple:
if (checked) {
counter++;
fruits[1] = counter;
} else {
counter--;
fruits[1] = 0;
}
break;
//OTHER CASES
}
}
Yes this is possible with Checkboxes, take a look here:
http://stackoverflow.com/questions/3149414/how-to-receive-a-event-on-android-checkbox-check-change
If I understood you right, you just have to set a variable when the user clicks on one of those checkboxes like:
var number1 = 'Mango'
You should achive this with the example you can find in the link above.

onclick not working in resume method

i have a problem in my application, i have a formulaire whish a user should fill information and save it to database,i have both Edit Text and Radio Button :
rm_1 = (EditText) findViewById(R.id.rm_1);
rm_2 = (EditText) findViewById(R.id.rm_2);
rm_3 = (EditText) findViewById(R.id.rm_3);
rm_13_1 = (RadioButton) findViewById(R.id.rm_13_1);
rm_13_2 = (RadioButton) findViewById(R.id.rm_13_2);
rm_14_1 = (RadioButton) findViewById(R.id.rm_14_1);
rm_14_2 = (RadioButton) findViewById(R.id.rm_14_2);
rm_14_3 = (RadioButton) findViewById(R.id.rm_14_3);
i have a method Onclick whish associate each radio buton selected with a value :
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((Checkable) view).isChecked();
switch (view.getId()) {
case R.id.rm_13_1:
if (checked)
a = 0;
break;
case R.id.rm_13_2:
if (checked)
a = 1;
break;
case R.id.rm_14_1:
if (checked)
b = 0;
break;
case R.id.rm_14_2:
if (checked)
b = 1;
break;
case R.id.rm_14_3:
if (checked)
b = 2;
break;
case R.id.rm_14_4:
if (checked)
b = 3;
break;
}
until now everything works fine, the user writes in the edit text and select the radio button , and in database i find the same information.
in order to save the data entered by the user i did used shared preferences, so the text writing by the user and radio button selected appear again when the user returns to the activity.
That's when the issue occurs when a user change the activity , so if he returns to the activity he finds the radio button already selected but when he click on save button the value he gets in database is zero, it is like the methode :
public void onRadioButtonClicked(View view)
is not working, i don't know why ?? the user need to click again on radio button to have the values assigned in the method onRadioButtonClicked(View view), so how to solve that ?
this is where i save data :
Button bton = (Button) findViewById(R.id.ajoutUn);
bton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ajouter(v);
}
public void ajouter(View v) {
db.open();
db.insertMENAGE(rm_1ts, rm_2ts, rm_3ts, rm_4ts, rm_5ts,
rm_6ts, rm_7ts, rm_8ts, rm_9ts, rm_10ts, rm_11ts,
a, b, rm_14_4_autrets, rm_15ts);}}
And the method in database is :
public long insertMENAGE(String Region, String Provence_prefecture , String Commune_Arrondissement ,String N_district, String N_M_district , String N_menage_logement, String Adresse_menage , String Nom_Enqueteur, String code_enquêteur , String Date_realisation_enquête, String Nom_controleur , String Date_controle, int echantillon_principal, int Statut_enquêté , String autre, String Observations ) {
ContentValues initialValues = new ContentValues();
initialValues.put(col_Commune_Arrondissement,Commune_Arrondissement);
initialValues.put(col_N_district,N_district);
initialValues.put(col_N_M_district,N_M_district);
initialValues.put(col_N_menage_logement,N_menage_logement);
initialValues.put(col_Adresse_menage,Adresse_menage);
initialValues.put(col_Nom_Enqueteur,Nom_Enqueteur);
initialValues.put(col_code_enquêteur ,code_enquêteur);
initialValues.put(col_Date_realisation_enquête,Date_realisation_enquête);
initialValues.put(col_Nom_controleur,Nom_controleur);
initialValues.put(col_Date_controle,Date_controle);
initialValues.put(col_echantillon_principal,echantillon_principal);
initialValues.put(col_Statut_enquêté,Statut_enquêté);
initialValues.put(col_Observations,Observations);
return db.insertOrThrow(MENAGE,null, initialValues);
}
Check all your radio button values at your onResume() method like following, and assigning values to your variable.
if(rm_13_1.isChecked())
{
}
else if(rm_13_2.isChecked())
{
}
else if(rm_14_1.isChecked())
{
}
else if(rm_14_2.isChecked())
{
}
else if(rm_14_3.isChecked())
{
}
Hope it will work
First of all I'm posting this an answer because the text is too large.
Either there's some meaningful code that we're not seeing, or there's a problem understanding a few things.
The method onRadioButtonClicked(View view) is only called when the user clicks the radioButton. When the user comes back from another Activity the button is already selected. This is correct, and this is how it should behave. As far as I can see, this code only affects variables 'a' and 'b'.
On the other hand you say that you have a separate 'save' button. When the user comes back from another Acivity, variables 'a' and 'b' should preserve their values, and the results of your 'save' code should work.
I know this is not an answer, just a few insights that hopefully help you in some way.

android xml reference not working with switch and case with static array

I'm trying to make my life a heck of a lot easier by cycling through buttons in my xml (because I have a ton of buttons). Why isn't this working?
Button bf[];
public static final int[] Buttons = { R.id.b1, R.id.b2, R.id.b3, R.id.b4,
R.id.b5, R.id.b6, R.id.b7, R.id.b8, R.id.b9, R.id.bBack,
R.id.bClearAll, R.id.bClear };
I have a static final int that holds some of my buttons, which is list in the header.
Within my onCreate method I set up my buttons:
for (int i = 1; i < 10; i++) {
bf[i] = (Button) findViewById(Buttons[i - 1]);
bf[i].setOnClickListener(this);
}
Nice and easy right? but then when I try to reference them in the switch and case (within my implemented onClickListener method, I'm having problems:
for (int i = 1; i < 10; i++) {
case Buttons[i-1]:
Toast.makeText(this, bf[i].getText(), Toast.LENGTH_SHORT).show();
break;
}
This doesn't work, so then I just tried a single reference:
switch (v.getId()) {
case Buttons[0]:
Toast.makeText(this, bf[1].getText(), Toast.LENGTH_SHORT).show();
break;
which doesn't work either?!?! Help please?
v is your View in the onClickListener, right?
Why don't you use:
Button b = (Button) v;
Toast.makeText(this, b.getText(), Toast.LENGTH_SHORT).show();
Some other points:
You did not post the complete code but I guess you can change your Buttons array to private.
Probably you don't even need bf[]
Edit: Also I'd suggest to use this for-loop to cycle through all of your buttons to make it more flexible:
for (int i : Buttons) {
Button b = findViewById(i);
b.setOnClickListener(myClickListener);
}

Dynamically creating Buttons and setting onClickListener

I have problem with handling dynamically created Buttons on Android. I'm creating N buttons and I have to do the same method when button is clicked but I have to know which button is clicked.
for (int i = 0; i < NO_BUTTONS; i++){
Button btn = new Button(this);
btn.setId(2000+i);
...
btn.setOnClickListener((OnClickListener) this);
buttonList.addView(btn);
list.add(btn);
Cucurrently I'm adding ID to every button and I'm using the method below to see which button was clicked. (line btn.setId(2000+i); and btn.setOnClickListener((OnClickListener) this);). This method is also implemented in the activity.
#Override
public void onClick(View v) {
switch (v.getId()){
case 2000: selectButton(0);
break;
...
case 2007: selectButton(7);
break;
}
}
This doesn't look good to me so i'm asking is there some better way to do this? or how to send some information to onclick event? any suggestions?
You could create a method that returns an onclickListener and takes a button as a parameter. And then use that method to set the onClicklistener in the first loop you have..
Update: code could be soemthing along these lines:
View.OnClickListener getOnClickDoSomething(final Button button) {
return new View.OnClickListener() {
public void onClick(View v) {
button.setText("text now set.. ");
}
};
}
as a method in the activity and then use it in the loop like this
button.setOnClickListener(getOnClickDoSomething(button));
I got one solution for this..
use this code in onCreate
linear = (LinearLayout) findViewById(R.id.linear);
LayoutParams param = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1.0f);
Button[] btn = new Button[num_array_name.length];
for (int i = 0; i < num_array_name.length; i++) {
btn[i] = new Button(getApplicationContext());
btn[i].setText(num_array_name[i].toString());
btn[i].setTextColor(Color.parseColor("#000000"));
btn[i].setTextSize(20);
btn[i].setHeight(100);
btn[i].setLayoutParams(param);
btn[i].setPadding(15, 5, 15, 5);
linear.addView(btn[i]);
btn[i].setOnClickListener(handleOnClick(btn[i]));
}
after onCreate create one method of return type View.OnClickListener like this..
View.OnClickListener handleOnClick(final Button button) {
return new View.OnClickListener() {
public void onClick(View v) {
}
};
}
Button.OnClickListener btnclick = new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Button button = (Button)v;
Toast.makeText(getApplicationContext(), button.getText().toString(),2).show();
}
};
call this listener by btn.setOnClickListener(btnclick);
View IDs should not be used for these purposes as View Ids are generated on compilation time depending on IDs defined in xml layout files.
Just place your own IDs in the setTag() method which is available at the View level (so Buttons inherit them). This "tag" can be anything that allow you to recognize a View from others. You retrieve its value with getTag().
instead use setTag() function to distinct easily.
for(int i=0;i<4;i++) {
Button btn = new Button(this);
btn.setTag(i);
btn.setOnClickListener(new View.OnclickListener() {
#Override
public void onClick(View v) {
int i=v.getTag();
switch(i) {
case 1: btn.setText(i);
break;
case 2: btn.setText(i);
break;
case 3: btn.setText(i);
break;
case 4: btn.setText(i);
break;
default: btn.setText("Others");
}
}
}
"This doesn't look good to me" why not? doesn't it work? You could also create a static member variable holding a list of all added buttons, and then look for the clicked button in that list instead.
I don't know why you would want to create N buttons, it looks like your value of N is greater than 10 at least, if you are not trying to show them all at once (I mean fit all of them into one single screen, no scrolling) you could try to recycle the invisible buttons just like we do for list view using a list view holder. This would reduce your memory footprint and boost performance, and differentiate the buttons based either on the text you set on them or a tag or you can even hold a reference to those small number of buttons.
Is preferable not to mess up with the ids, setTag and getTag methods were designed for that purpose, it's the fast and clean way to set a bunch of button listeners on a dynamic layout
This answer may you help:
https://stackoverflow.com/a/5291891/2804001
public class MainActivity extends Activity implements View.OnClickListener
{
LinearLayout linearLayout;
Button [] button;
View.OnClickListener listener;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
linearLayout=(LinearLayout)findViewById(R.id.parent_lay);
String[] array={"U123","U124","U125"};
int length=array.length;
System.out.println("11111111111111111111111111");
button=new Button[length];
for(int i=0;i<length;i++)
{
button[i]=new Button(getApplicationContext());
button[i].setId(i);
button[i].setText("User" + i);
button[i].setOnClickListener(this);
linearLayout.addView(button[i]);
}
}
#Override
public void onClick(View view)
{
view.getId();
Button button=(Button)findViewById(view.getId());
button.setText("Changed");
}
}

Android Dynamically Created Button: setOnClickListener doesn't work

The onClick never fires! Why not? Please help me.
for(int i = 0; i < 12; i++) {
String title = "Button" + i;
Button sliderButton = new Button(this);
sliderButton.setText(title);
glideMenuTray.addView(sliderButton,100,40);
sliderButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d("gm", "Tapped ");
}
});
}
I'm no expert at stuff like this, but it's probably something to do with garbage collection, and the OnClickListeners passing out of scope.
Though I don't think you can use the super-easy approach to onClickListeners that Dimitar mentions, you can probably use the middle approach that the section he links to discusses, even though it's not a new approach. To repeat the example code here, it's:
View.OnClickListener handler = View.OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case R.id.myButton: // doStuff
break;
case R.id.myOtherButton: // doStuff
break;
}
}
}
findViewById(R.id.myButton).setOnClickListener(handler);
findViewById(R.id.myOtherButton).setOnClickListener(handler);
If the only thing distinguishing the buttons is their title text, well, you could use that to distinguish between them in the master onClick method.
Also, not shure, I once had a problem like that on a TextView and it was because I didnt add setClickable(true)
My code was something like
TextView text = new TextView(this);
text.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
text.setText("***");
text.setClickable(true);
text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//My action
}
});
myViewGroup.addView(text );
Hope this helps
If you are using Donut or Eclair, you can use common click listener, registered in your Activity and hooked with your buttons in the layout XML.
For reference, look here, the category Easier click listeners.
Am I right in assuming that the following line:
glideMenuTray.addView(sliderButton,100,40);
Adds the view to the coords x:100,y:40 onto some View extending ViewGroup?
In that case you are stacking 12 buttons on top of each other, only the last Button (labeled Button11) will be visible (and clickable).
And provided that the question is 3 years old I really hope you already resolved this by now :)
set the setOnClickListener before adding the view.
for(int i = 0; i < 12; i++) {
String title = "Button" + i;
Button sliderButton = new Button(this);
sliderButton.setText(title);
sliderButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d("gm", "Tapped ");
}
glideMenuTray.addView(sliderButton,100,40);
}

Categories

Resources