generically match a button with id - android

I created buttons in my xml layout, each gets an id : button1,button2 and so on.
I want in my main activity to create a button array and loop for all buttons and reference them to the ids.
ImageButton btn = (ImageButton)this.findViewById (R.id.imageButton1);
ImageButton btn2 = (ImageButton)this.findViewById (R.id.imageButton2);
instead of doing this i want something like this:
ImageButton btn[];
for(int i=0;i<numOfButtons;i++)
{
btn[i] = (ImageButton)this.findViewById (R.id.("imageButton"+(i+1)));
}

ImageButton btn[];
int[] btnIDs = new int[] {R.id.btn1, R.id.btn2, R.id.btn3,R.id.btn4, ... }
for(int i=0; i<btnIDs.length; i++) {
btn[i] = (ImageButton) findViewById(btnIDs[i]);
}

You cannot take id's generically like that.
But instead of this you can take buttons in a loop if layout looks like:
<layout>
<button>
<button>
<button>
...
<button>
</layout>
then,
for (int i = 0; i < layout.getChildCount; i++)
button[i] = layout.getChild(i);

Related

can LinearLayout put two items on the same line?

I have the code as below, and I need 2 things:
I wish to put tv[i] on the same line as txt[i]
and I want keyboard to appear after touching tv[i].
I'm a complete beginner to Android. Thank you.
public void click2(View view) {
Button button3 = findViewById(R.id.button2);
button3.setText("hello");
// Button[] buttons = new Button[10](this);
/*
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.activity_main);
Button txt1 = new Button(this);
// linearLayout.setBackgroundColor(Color.TRANSPARENT);
linearLayout.addView(txt1);
*/
Integer.toBinaryString(12);
// Put buttons into an array
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.activity_main);
// GridLayout gridLayout=(GridLayout) findViewById(R.id.activity_main);
// Put buttons into an array
// Button[] txt = {new Button(this), new Button(this)};
Button[] txt = new Button[8];
TextView[] tv = new TextView[8];
// loop over all values of i between 0 to the end of the button array
for (int i = 0; i < txt.length; i = i + 1) {
// Access array elements by index so txt1 is txt[1], etc.
txt[i]=new Button(this);
txt[i].setText(Integer.toBinaryString(i));
linearLayout.addView(txt[i]);
tv[i]=new TextView(this);
linearLayout.addView(tv[i]);
}
};
MAYBE I'm putting your line
linearLayout.setOrientation(LinearLayout.HORIZONTAL);
at a wrong place.
KOD MainActivity.java
public void click2(View view) {
Button button3 = findViewById(R.id.button2);
button3.setText("hello");
// Put buttons into an array
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.activity_main);
// GridLayout gridLayout=(GridLayout) findViewById(R.id.activity_main);
// Put buttons into an array
// Button[] txt = {new Button(this), new Button(this)};
Button[] txt = new Button[8];
TextView[] tv = new TextView[8];
// loop over all values of i between 0 to the end of the button array
for (int i = 0; i < txt.length; i = i + 1) {
linearLayout.setOrientation(LinearLayout.HORIZONTAL);
// Access array elements by index so txt1 is txt[1], etc.
txt[i]=new Button(this);
txt[i].setText(Integer.toBinaryString(i));
linearLayout.addView(txt[i]);
tv[i]=new TextView(this);
linearLayout.addView(tv[i]);
}
};
Call
linearLayout.setOrientation(LinearLayout.VERTICAL);
to make 2 items appear side by side.
For showing keyboard, take a look here:
How do you close/hide the Android soft keyboard programmatically?
Looks like you are referencing your xml file here:
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.activity_main);
You should go to your xml file, add a id (android:id="#+id/some_id") tag to your <LinearLayout> and use this id in your LinearLayout linearLayout =(LinearLayout) findViewById(R.id.HERE)
Other option is to go to your xml file and add sandroid:orientation="horizontal" like this:
<LinearLayout
android:id="#+id/some_id"
android:orientation="vertical"
...>

assign different button names to id using for loop

I have an 5 buttons and I need to explicitly create each editText. I found a solution by using for loop we can group the buttons. like below.
private Button[] btn = new Button[4];
private int[] btn_id = {R.id.btn0, R.id.btn1, R.id.btn2, R.id.btn3};
for(int i = 0; i < btn.length; i++){
btn[i] = (Button) findViewById(btn_id[i]);
btn[i].setBackgroundColor(Color.rgb(207, 207, 207));
btn[i].setOnClickListener(this);
}
Here I need to use the same button only. How can I use the above code for the different button names?
private Button btn1,button2,bt3,b4;
How can I achieve the for loop for the above button declaration. I tried to add the all the button in to an arrayList bu that doesn't work. Any suggestions.
You can try this way, Hope this help you!
for(int i = 0; i < btn.length; i++){
int btnId= mContxt.getResources().getIdentifier("btn_"+i, "id", getPackageName());
Button btn = (Button)findViewById(buttonId);
btn.setBackgroundColor(Color.rgb(207, 207, 207));
btn.setOnClickListener(this);
}
After the for-loop you have this array filled with Buttons,
private Button[] btn = new Button[4];
Then you can just do this, after the for-loop
private Button btn1 = btn[0];
private Button btn2 = btn[1];
private Button btn3 = btn[2];
private Button btn4 = btn[3];
You can do this in a better way, but I hope this will give you a small indication on how to do it.

How to get all Buttons ID's in one time on Android

I have 16 Buttons in my Activity and I have to initialize those inside onCreate().
Is there any way to initialize all buttons in one single line code?(loops etc.)
Code should take all buttons R.id. from XML Layout and process....
Let's say you named your button button_0, button_1, .. button_15. You can do:
for (int i = 0; i < 16; i++) {
int id = getResources().getIdentifier("button_"+i, "id", getPackageName());
button[i] = (Button) findViewById(id);
}
Well, if all 16 of those buttons are inside one view or layout, then you could do the following.
ArrayList<View> allButtons;
allButtons = ((LinearLayout) findViewById(R.id.button_container)).getTouchables();
This assumes that your container (in this example a LinearLayout) contains no Touchable that is not a Button.
use Butterknife view injections library
Download Android ButterKnife Zelezny plugin for Android Studio or Intellij IDEA
and initialize all your views from current layout by 1 click
For xamarin android :
List<Button>() allButtons = new List<Button>();
for (int i = 1; i < 15; i++)
{
int id = this.Resources.GetIdentifier("btn" + i.ToString(), "id", this.PackageName);
Button btn = (Button)FindViewById(id);
allButtons.Add(btn);
}
This method takes all buttons inside the layout, hope it helps. Easy to implement & you can use it for almost every project, no libraries required.
public List<Button> getAllButtons(ViewGroup layout){
List<Button> btn = new ArrayList<>();
for(int i =0; i< layout.getChildCount(); i++){
View v =layout.getChildAt(i);
if(v instanceof Button){
btn.add((Button) v);
}
}
return btn;
}
Example
List<Button> btn_list = getAllButtons(myRelativeLayout);
Button my_btn = btn_list.get(0);
my_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("btn_test", "onClick: hello");
}
});
If you are using Kotlin, and your buttons have ids in the form of button1, button2... button16, you can do something like this:
var btn = ArrayList<Button>(16)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_game_screen)
for(i in 0 until 16) {
var id = resources.getIdentifier("button"+(i+1), "id", packageName)
btn.add(findViewById<View>(id) as Button)
btn[i].setText("something") //or do whatever now
}
}
If you only know the container id or the button ids are all different try this:
Activity(on create method before setContentView)
List<Integer> idButtons= new ArrayList<>();
//container_button is my button container
RelativeLayout containerButton = findViewById(R.id.container_button);
for(int i =0; i < containerButton.getChildCount(); i++){
View v = containerButton.getChildAt(i);
if(v instanceof Button){
idButtons.add(((Button) v).getId());
}
}
Layout
<RelativeLayout
android:id="#+id/container_button"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:layout_weight="1"
android:layout_marginEnd="0dp">
<Button
android:id="#+id/buttonac"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/red_button"
android:textColor="#android:color/white"
android:text="AC"
android:onClick="pulsacion" />
<Button
android:id="#+id/buttondel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/buttonac"
android:layout_alignBottom="#+id/buttonac"
android:background="#drawable/red_button"
android:textColor="#android:color/white"
android:text="DEL"
android:onClick="pulsacion" />
[...]
</RelativeLayout>

Shuffle Button with position Android

I have ten buttons in my xml layout i want to exchange the position of the 10 buttons randomly. I tried two methods to achieve it.
Method 1: I changed the background resource of the button but only the image changed. Not the button position on the layout. Here is my workings for method 1.
objects = new ArrayList<Integer>();
objects.add(R.drawable.num_one);
objects.add(R.drawable.num_eight);
objects.add(R.drawable.num_six);
objects.add(R.drawable.num_five);
objects.add(R.drawable.num_nine);
objects.add(R.drawable.num_four);
objects.add(R.drawable.num_two);
objects.add(R.drawable.num_three);
objects.add(R.drawable.num_zero);
objects.add(R.drawable.num_seven);
// Shuffle the collection
Collections.shuffle(objects);
List<Button> buttons = new ArrayList<Button>();
buttons.add((Button)findViewById(R.id.name));
buttons.add((Button)findViewById(R.id.boutton_eight));
buttons.add((Button)findViewById(R.id.boutton_six));
buttons.add((Button)findViewById(R.id.boutton_five));
buttons.add((Button)findViewById(R.id.time));
buttons.add((Button)findViewById(R.id.boutton_four));
buttons.add((Button)findViewById(R.id.boutton_two));
buttons.add((Button)findViewById(R.id.search_box));
buttons.add((Button)findViewById(R.id.boutton_zero));
buttons.add((Button)findViewById(R.id.boutton_seven));
for (int i = 0; i < objects.size(); i++) {
buttons.get(i).setBackgroundResource(objects.get(i));
}
In Method two: I shuffled the button directly but as the widget are already set in the xml layout. AddView () give an error message that the view is already set. Here is my working for the second solution.
ll = (LinearLayout)findViewById(R.id.llShuffleBox);
//create another two linear layouts which will host 5 buttons horizontally
top_compte = (LinearLayout)findViewById(R.id.top_compte);
bottom_calculator= (LinearLayout)findViewById(R.id.bottom_calculator);
buttons.add((Button)findViewById(R.id.name));
buttons.add((Button)findViewById(R.id.boutton_eight));
buttons.add((Button)findViewById(R.id.boutton_six));
buttons.add((Button)findViewById(R.id.boutton_five));
buttons.add((Button)findViewById(R.id.time));
buttons.add((Button)findViewById(R.id.boutton_four));
buttons.add((Button)findViewById(R.id.boutton_two));
buttons.add((Button)findViewById(R.id.search_box));
buttons.add((Button)findViewById(R.id.boutton_zero));
buttons.add((Button)findViewById(R.id.boutton_seven));
Collections.shuffle(buttons);
for (int i=0;i<5;i++) {
top_compte.addView(buttons.get(i));
}
//add remaining 5 to second layout
for (int i=5;i<10;i++){
bottom_calculator.addView(buttons.get(i));
}
// ll.addView(top_compte);
ll.addView(bottom_calculator);
My question is how can i exchanged the position of the buttons on my layout. Note button 0 to 4 is in a horizontal linear layout and below it is the second horizontal linear layout containing button 5 to 9. Also ll is the Main LinearLayout that contain the two horizontal layout.
You can try creating the Buttons dynamically(in code). So, you'll have a LinearLayout(vertical) and two LinearLayouts(horizontal) within it. Keep your xml file as:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/llShuffleBox"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/top_compte"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
</LinearLayout>
<LinearLayout
android:id="#+id/bottom_calculator"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
</LinearLayout>
</LinearLayout>
Now, for the activity code:
ll = (LinearLayout)findViewById(R.id.llShuffleBox);
//create another two linear layouts which will host 5 buttons horizontally
top_compte = (LinearLayout)findViewById(R.id.top_compte);
bottom_calculator= (LinearLayout)findViewById(R.id.bottom_calculator);
// Create an ArrayList to hold the Button objects that we will create
ArrayList<Button> buttonList = new ArrayList<Button>();
// Create the Buttons, set their text as numeral value of the index variable
for (int i = 0; i < 10; i++) {
Button b = new Button(this);
b.setText("" + (i+1));
b.setGravity(Gravity.CENTER_HORIZONTAL);
buttonList.add(b);
}
// Shuffle
Collections.shuffle(buttonList);
for (int i = 0; i < 10; i++) {
// Add the first five Buttons to top_compte
// Add the last five Buttons to bottom_calculator
if (i < 5) {
top_compte.addView(buttonList.get(i));
} else {
bottom_calculator.addView(buttonList.get(i));
}
}
Edit 1:
Declare and initialize this global variable:
// Global variable
int id = 1;
Add the following method to your activity. It will generate an id that is not in use elsewhere in your view tree.
// Generates and returns a valid id that's not in use
public int generateUniqueId(){
View v = findViewById(id);
while (v != null){
v = findViewById(++id);
}
return id++;
}
Change the code to set ids to buttons:
ll = (LinearLayout)findViewById(R.id.llShuffleBox);
//create another two linear layouts which will host 5 buttons horizontally
top_compte = (LinearLayout)findViewById(R.id.top_compte);
bottom_calculator= (LinearLayout)findViewById(R.id.bottom_calculator);
// Create an ArrayList to hold the Button objects that we will create
ArrayList<Button> buttonList = new ArrayList<Button>();
// Create the Buttons, set their text as numeral value of the index variable
for (int i = 0; i < 10; i++) {
Button b = new Button(this);
b.setText("" + (i+1));
b.setGravity(Gravity.CENTER_HORIZONTAL);
b.setId(generateUniqueId()); // Set an id to Button
buttonList.add(b);
}
// Shuffle
Collections.shuffle(buttonList);
for (int i = 0; i < 10; i++) {
// Add the first five Buttons to top_compte
// Add the last five Buttons to bottom_calculator
if (i < 5) {
top_compte.addView(buttonList.get(i));
} else {
bottom_calculator.addView(buttonList.get(i));
}
}
You can retrieve the ids using the getId() method. If you do not want to use the generateUniqueId() method, you can try replacing the line b.setId(generateUniqueId()); with b.setId(i + 1);. This will set the button ids from 1 to 10. But, it can be problematic if some view in your view hierarchy has the same id as any other.
Edit 2:
Here is how you can set the OnClickListeners to the Buttons you create dynamically:
for (int i = 0; i < 10; i++) {
final Button b = new Button(this);
b.setText("" + (i+1));
b.setGravity(Gravity.CENTER_HORIZONTAL);
b.setId(i + 1);
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
dealWithButtonClick(b);
}
});
bList.add(b);
}
And here is one possible implementation of dealWithButtonClick(Button) method. You can change it to suit your needs:
public void dealWithButtonClick(Button b) {
switch(b.getId()) {
case 1:
b.setBackground(getResources().getDrawable(R.drawable.some_drawable_1));
break;
case 2:
b.setBackground(getResources().getDrawable(R.drawable.some_drawable_2));
break;
........
........
........
case 10:
b.setBackground(getResources().getDrawable(R.drawable.some_drawable_10));
break;
default:
b.setBackground(getResources().getDrawable(R.drawable.some_drawable_for_when_no_cases_were_matched));
break; }
}
I had a same problem (shuffle buttons) and i come up with an easy solution
I just used an array of integer numbers of buttons ids and simple shufle. In my case was that enough. It's simple and u get the same result.
Integer[] a = { 0x7f090049, 0x7f09004b, 0x7f09004c, 0x7f090048};
Collections.shuffle(Arrays.asList(a));
button1 = (Button)findViewById(a[0]);
button2 = (Button)findViewById(a[1]);
button3 = (Button)findViewById(a[2]);
button4 = (Button)findViewById(a[3]);
I hope this will help.
Regards !!
(srry for my broken english)

Retrieve Group of Buttons in Main.xml

I created nine Button view in the main.xml and named it to Button1, Button2... Button9.. Then in my code I created an ArrayList of Button and its obvious that this array of buttons will hold my Button in the main.xml and in my current knowledge that to get the Button in my main.xml I need to use the findViewById method and basically I need to loop the array to get the button
ArrayList<Button> buttons;
int MAXBTN = 9;
for( int i = 0; i < BTN; i++ )
{
// Code here to use the findViewById method to get the button
}
And my problem is that I need to pass R.id.Button1 .. R.id.Button3 to the findViewById method, but I need to loop this. Is there anyway I can pass a counter in the findViewById while loop?
Please advise.
You can try this.
ArrayList<Button> buttons;
int MAXBTN = 9;
for( int i = 0; i < BTN; i++ )
{
String buttonID = "Button" + i+1 ;
int resID = getResources().getIdentifier(buttonID, "id", "packageName");
buttons.get(i) = ((Button) findViewById(resID));
}
I think there is already a same question asked for this check this
Its always better to search first before asking

Categories

Resources