Setting Button ID programmatically - android

Android 2.3.3
I have a table with N rows and N columns. For each row, I should add 4 buttons dynamically, and later do actions based on the button clicked. I know we can set the button IDs with Integer values with button.setID(), but I want to know whether we can set IDs as string values as we set in XML files, such as btnXYZ1 and btnXYZ2 etc.,

You can use tags for that purpose . For example
btn.setTag("btXYZ");

for (int i=0;i<nob;i++) {
Button btn = new Button(this);
btn.setId(i+1);
btn.setText("Button"+(i+1));
btn.setOnClickListener(btnclick); <<<<<<<set click
btn.setLayoutParams(lprams);
dynamicview.addView(btn);
}
And add this listner outside the any method and inside class
OnClickListener btnclick = new OnClickListener() {
#Override
public void onClick(View view) {
switch(view.getId()) {
case 1:
//first button click
break;
//Second button click
case 2:
break;
case 3:
//third button click
break;
case 4:
//fourth button click
break;
.
.
.
default:
break;
}
}
};

The strings you use in your XML files correspond to an int in R.java, and are hence actually ints. The setId() method will only accept an int value as an argument. You could define your IDs in a constants file, something like:
public class Ids {
public static final int ID_ONE = 1;
}
and then use it as:
button.setId(Ids.ID_ONE);

No you cannot set it to String, the id is int value, even when you set it from XML it is just the resource name of an int value

No you cannot set it to String, the id is int value, even when you set it from XML it is just the resource name of an int value

If you have the references to the views anyway , you can simply save them all into a HashMap, for example using HashMap .
Another alternative , so that you will avoid any typos , is to have an enum as the key of the hashMap , for example : HashMap .

Related

Calling .getBackground() in universal onClick method

I want to include many buttons in my app, which can play a sound by clicking, so I included an OnClick event.
#Override
public void onClick(View view) {
int id = view.getId();
final MediaPlayer mediaPlayer = new MediaPlayer();
switch (id) {
case R.id.whisteling_bird:
stopandPlay(R.raw.whisteling_bird, mediaPlayer);
break;
default:
break;
}
}
But now I have the following problem:
I also want to change the Alpha value of the button by using
.getBackground().setAlpha(64);
But what do I have to write before .getBackground()?
I donĀ“t want to write this
final Button whisteling_bird = (Button) view.findViewById(R.id.whisteling_bird);
whisteling_bird.setOnClickListener(this);
whisteling_bird.getBackground().setAlpha(64);
for every single button. What can I do?
In your onClick(), below id line,
put view.getBackground().setAlpha(64);
it will set every clicked view's alpha to 64. But you will also need to reset it somewhere for safety.

How can I change background color of all xml pages through three radio buttons

How can I change background color of all xml pages through three radio buttons, one is Red, another is Blue, and other is Green. When I will click onto one of them, then the background color of all XML pages will be changed into that selected color. Pls help me.
You should findViewById() your root layout and set within the method setBackgroundColor(). And by switching RadioButton you specify different color. See example below.
RelativeLayout rLayout = (RelativeLayout) findViewById(R.layout.the_id);
RadioButton rb = (RadioButton) findViewById(R.id.yourFirstRadioButton);
rb.setOnClickListener(listener);
and then:
OnClickListener listener = new OnClickListener (){
public void onClick(View v) {
switch(v.getId()){
case 0: //assume 0 is red
rLayout.setBackgroundColor(Color.parseColor(Color.RED));
break;
case 1: //assume 1 is blue
rLayout.setBackgroundColor(Color.parseColor(Color.BLUE));
break;
case 2: //assume 2 is green
rLayout.setBackgroundColor(Color.parseColor(Color.GREEN));
break;
}
}
}
If you want to change layout color in ALL Activities you should remember the value and pass it through Intent or declare static variable with the current color.See examples:
In Activity with RadioButtons:
Intent intent = new Intent(this, NextActivity.class);
intent.putExtra("color", green);
startActivity(intent);
And in NextActivity you get it like this:
Bundle bundle = getIntent().getExtras();
if(bundle != null){
switch(bundle.getInt("color")){
case 0: // 0 was red
rLayout.setBackgroundColor(Color.RED);
break;
case 1: // 1 was blue
rLayout.setBackgroundColor(Color.BLUE);
break;
case 2: // 2 was green
rLayout.setBackgroundColor(Color.GREEN);
break;
}
}
With the static variable I hope you know how to deal, so by switching RadioButton's you assign the value and in another Activity you check the value in switch/case statement as I described above.
Another common way is saving value in SharedPreferences. This is a good practice and it is light-weight, but also depends how many Activities you have. If just 2 - doesn't make sense, if 10 - yes. Nice answer is given here.
That's it. Good luck.
do it with custom theme set it dynamically by setTheme() method check below link
set theme dynamically
This is one option:
You can save in SharedPreferences the color you toggled. For example:
Create your SharedPreferences reference:
SharedPreferences prefs = getActivity().getSharedPreferences( getActivity().getPackageName(),Context.MODE_PRIVATE);
Then when you select a color (for example blue) do:
prefs.edit().putInt("TAG", Color.Blue).apply();
Then on any Activity onCreate method (after the setContentView call) or if its a fragment on onViewCreatedMethod you do:
If Activity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout."layout_id");
SharedPreferences prefs = getActivity().getSharedPreferences(getActivity().getPackageName(),Context.MODE_PRIVATE);
int backgroundColor = prefs.edit().getInt("TAG")
View rootView = findViewById(R.id."layout_id");
rootView.setBackgroundColor(backgroundColor);
}
if Fragment:
public void onViewCreated(View view, Bundle savedInstanceState) {
SharedPreferences prefs = getActivity().getSharedPreferences(getActivity().getPackageName(),Context.MODE_PRIVATE);
int backgroundColor = prefs.edit().getInt("TAG")
view.setBackgroundColor(backgroundColor);
}
This way, when you load a page the color of its background will be changed to the one you've store in preferences.

I have 200 textviews and i want to know which one was pressed then how to change the text

I have a problem... have been thinking about it for a while now and been looking on line and still haven't come up with a clear explanation...
I have a number of textviews and have set onClickListeners to each of them.. and when the user clicks on one of them I want them to have the ability to change the text to another set of string array options which I have created progammatically. When the user selects an option the text should change to the option they choose. (I.e. TextView was A now it is B. hope this makes sense.. anyway... )
The current solution was to set a OnClickListener to every TextView and when someone pressed it an individual dialog showed. But I found that if I do this the code would be so long it would take an eternity to code so am hoping someone has a more elegant way of coding such a long process =(
So I guess my question would be... 1) is there a way I can find out which text view was pressed and then change the text of that TextView being pressed within a single method? to save me having to code 1000 alert dialogs...
http://i.stack.imgur.com/LRJGz.png
I would advise you to use a grid view.
You can see which textview was pressed like this:
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
//get id
switch (v.getId()) {
case R.id.textView1: ...
}
});
One of the ways to do what you want is to use the text view setTag() and getTag() methods.
On init of a text view use the setTag() to set some value to identify the view.
In the on click event use the getTag() on the view argument to know which view was clicked.
I would suggest holding the textviews in an array, like so:
TextView[] textViewArray = new TextView[textViewCount];
Then using a for loop assign each one a tag of integer - it's position
textViewArray.setTag(i)
And add an onClickListener to each one, again using a for loop:
textviewArray[i].setOnClickListener(etc...)
Then when one is clicked, you can use get the position of view that was clicked. This will require a custom method inside of your:
textviewArray.setOnClickListener(new customOnClickListener())
Where your customOnClickListner is like this:
private class customOnClickListener implements CompoundButton.{
public void OnClick(View view){
int position = (Integer) view.getTag()
///Do more code here - your processing
}
}
Hope that makes sense :)
For your for loops, you could use for(i = 0, i
Use set id for all text, where set the id positive integer(distinct), and then have one on view click listener(set it all) where u catch all text view clicks(downcast view with textview) and in side it put a switch case where you handle clicks on which text view is clicked.
You have to set "onClickListner" on all of of your textview.
For Saving some length of code i would suggest you create a function of your dialogbox, and give some int parameter to it, which would be directly called by the clickListener of textview,
Like ,
int i=0;
......
textView1 = (TextView)findViewById(R.id.yourtextview1);
textView2 = (TextView)findViewById(R.id.yourtextview2);
......
......
// and so on, for your all textviews
#Override
public void onClick(View view) {
if (view.equals(textView1)) {
i = 1;
CustomDialog(i);
}
//Similarly for all your textViews..
..........
Make A function CustomDialog Like
public void CustomDialog(int i){
if(i==1){
//Do something
}
}

Android calculator buttons

I am trying to make a calculator for Android. Here is the code for my buttons:
int[] button_ids = {
R.id.BtnNum0, R.id.BtnNum1, R.id.BtnNum2, R.id.BtnNum3, R.id.BtnNum4, R.id.BtnNum5, R.id.BtnNum6,
R.id.BtnNum7, R.id.BtnNum8, R.id.BtnNum9, R.id.BtnAdd, R.id.BtnSub, R.id.BtnDiv, R.id.BtnMult,
R.id.BtnClear, R.id.equals
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditTextValue = (EditText) findViewById(R.id.editText1);
TVValue = (TextView) findViewById(R.id.textView1);
buttons = new ArrayList<Button>();
for(int id : button_ids) {
Button button = (Button)findViewById(id);
button.setOnClickListener(this);
buttons.add(button);
}
}
How I can change this part to a block of code where I won't have to declare the IDs of the buttons? (e.g. R.id.BtnNum0)
int[] button_ids = {
R.id.BtnNum0, R.id.BtnNum1, R.id.BtnNum2, R.id.BtnNum3, R.id.BtnNum4, R.id.BtnNum5, R.id.BtnNum6,
R.id.BtnNum7, R.id.BtnNum8, R.id.BtnNum9, R.id.BtnAdd, R.id.BtnSub, R.id.BtnDiv, R.id.BtnMult,
R.id.BtnClear, R.id.equals
};
I have been searching for an answer, but I still can't find a solution.
What you can do, since this code seems to only set a single OnClickListener for all Buttons, is to do it in xml
For each Button set
android:onClick="functionName"
then in your code you can do away with all of the id's and your for loop. In Java just create a function like
public void functionName(View v)
{
switch (v.getId())
{
case R.id.buttonId:
// do work for this Button
break;
...
}
The way you are doing it is fine but this is how I prefer to handle this situation. You just have to give all of the Buttons the same function name in xml then use that name as your function name in Java. You also just have to be sure to declare the function with a void return type and make sure it takes a View as its one and only parameter as in my example.
The Button Docs also have an example of this
in your layout file add this to every button
<Button
...
android:onClick="btnClicked"
.../>
then in your code add this method and check for each button in this method
public void btnClicked(View v)
{
switch(v.getId())
{
case R.id.BtnNum0:
// your code
break;
....
}
}
That is likely the best solution unfortunately, unless you use some sort of annotation framework which still doesn't cut down much on the boilerplate.
edit:
You could try to get a pointer to whatever ViewGroup is holding the Button views and then getting all of its children, and then looping through them while casting them to Buttons as you go.
For example: If your Button objects in XML are housed in a LinearLayout, you could get the pointer to that and do something like this:
for(int i=0; i < ((ViewGroup)v).getChildCount(); ++i) {
Button nextChild = (Button) ((ViewGroup)v).getChildAt(i);
}
Of course, I recommend against this, but it is still a possibility.
As trevor-e suggested, you can give an annotation processor a try. Android Annotations can simplify your code to:
#Click
public void BtnNum0() {
// Button 0 clicked
}
#Click
public void BtnNum1() {
// Button 1 clicked
}
// etc.
If you go this route, please do try to use names following the Java convention as the button names correspond with function names.

Some alternative to hundreds of buttons

Im going to write some android app, which will basically consists of two activities. So first should have a lot of buttons (100+) and on click on any of them I will just get some special id and move to second activity. But is there any alternative to declare that hundreds of buttons and copy/paste one piece of code to every of them setting almost same onClickLister? Is there any special construction? Thanks
Edit: every of buttons are actually indexed from 1 to n. And on the click second activity will be launched and get that index to show it. I cant basically use any spinner or smth else, because there will be 3 rows of clickable things and each of them carring different images
Edit 2: so, to give you an idea, im going to do some table of buttons like in Angry Birds menu when you actually choosing the level you want to play. So, on click you will get id of button and start second activity
Call the method to add buttons
private void addButton(){
LinearLayout view = (LinearLayout) findViewById(R.id.linear_layout_id_here);
Button btn = null;
int w = 50;
int h = 25;
for(int i=1; i<100; i++) {
btn = new Button(this);
btn.setLayoutParams(new LayoutParams(w,h));
btn.setText("button " +i);
btn.setTag(""+i);
btn.setOnClickListener(onClickBtn);
view.addView(btn);
btn = null;
}
}
Call this method for handling onclick on button
private View.OnClickListener onClickBtn = new View.OnClickListener() {
public void onClick(View view) {
final int tag = Integer.parseInt(view.getTag().toString());
switch (tag) {
case 1:
// Do stuff
break;
case 2:
// Do stuff
break;
default:
break;
}
}
};
You should use a ListView.
ListViews are great for handling a lot of items at the same time. They are also natural for the user. Additionally, you use only one click listener - OnItemClickListener.
There's a useful example on how to work with ListViews in the Android Referenence.
You may add buttons in code, something like this:
#Override
public void onCreate(Bundle savedInstanceState) {
/*your code here*/
GroupView gw =findViewById(R.id.pnlButtonscontainer); //find the panel to add the buttons
for(int i=0; i<100; i++) {
Button b = new Button(this);
b.setLayoutParameters(new LayoutParameters(w,h));
b.settext = i+"";
b.setOnClickListener(new OnClickListener(){
});
}
}
I coded directly into browser, so some syntax error may appear in my code, but this is the point, a way, not the only one, to add 100 buttons.

Categories

Resources