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>
Related
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);
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)
I have an application on which I apply some resources to buttons to modify their backgrounds.
All work well, but when my application goes to onResume after onPause, I'm not able to set the background anymore.
I have a set of 18 buttons, and when I am in onResume, i call:
for (int i = 0; i < max; i++) {
Button b = l.get(i);
b.setBackgroundResource(R.color.green);
}
In l i have the list of all buttons got from findViewById().
This works only for the last element of the for, but not for the others.
Any idea?
** Edit **
This is the code I use for populating the array
btn_1 = (Button)findViewById(R.id.btn_1);
btn_1.setOnClickListener(this);
l.add(btn_1);
this is repeated for all my buttons.
** Second edit **
public void onResume() {
btn_1 = (Button)findViewById(R.id.btn_1);
btn_1.setOnClickListener(this);
l = new ArrayList<Button>();
l.add(btn_1);
...
for (int i = 0; i < max; i++) {
Button b = l.get(i);
b.setBackgroundResource(R.color.green);
}
}
The same is done in onCreate().
try the d following.. this will works fine.
List<Button> mButtonList = new ArrayList<Button>();
onCreate() {
mButtonList.add((Button) findViewById(R.id.btn_1));
mButtonList.add((Button) findViewById(R.id.btn_2));
mButtonList.add((Button) findViewById(R.id.btn_3));
....
for(Button b : mButtonList) {
b.setOnClickListener(this);
}
}
onResume() {
for(Button b : mButtonList) {
b.setBackgroundResource(R.color.green);
}
}
Simple example:
Activity
public class StackOverFlowActivity extends Activity {
private ArrayList<Button> myArray = new ArrayList<Button>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myArray.add((Button)findViewById(R.id.btn_1));
myArray.add((Button)findViewById(R.id.btn_2));
myArray.add((Button)findViewById(R.id.btn_3));
myArray.add((Button)findViewById(R.id.btn_4));
myArray.add((Button)findViewById(R.id.btn_5));
}
#Override
protected void onResume() {
super.onResume();
for (Button b : myArray) {
b.setBackgroundColor(getResources().getColor(R.color.blue));
}
}
}
XML main
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="#+id/btn_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 1" />
<Button
android:id="#+id/btn_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 2" />
<Button
android:id="#+id/btn_3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 3" />
<Button
android:id="#+id/btn_4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 4" />
<Button
android:id="#+id/btn_5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 5" />
</LinearLayout>
My color in the Strings.xml
<color name="blue">#0099CC</color>
Use this instead:
for (int i = 0; i < max; i++) {
Button b = l.get(i);
b.setBackgroundColor(getResources().getColor(R.color.green));
}
If max is really big you might want to cache the getColor result before the loop.
EDIT:
According to the docs: setBackgroundResource is to be used with drawable ids only, and setBackgroundColor seems to be exactly what you need, so maybe another part of your code isn't working well, maybe the loop, the above line for setBackgroundColor works well on my app.
You've said:
": the ... code is the same for btn_1, just swap btn_1 with btn_2, btn_3 and so on. "
if so, than these lines are resetting your Array every time you try and add a new button.
l = new ArrayList<Button>();
l.add(btn_1);
P.S. you should avoid using a manual creation of buttons array - instead use some Parenting Layout such as LinearLayout and then fetch his button son's using getChildAt(i), It's much cleaner. Example:
// Register all the buttons in the layout to the OnClickListener
LinearLayout lin = (LinearLayout)findViewById(R.id.linear_buttons);
int childcount = lin.getChildCount();
for (int i=0; i < childcount; i++){
View v = lin.getChildAt(i);
v.setOnClickListener(this);
}
Try this --
for (int i = 0; i < l.getChildCount(); i++)
{
Button b = (Button) l.getChildAt(i);
b.setBackgroundResource(R.color.green);
}
try this. its working for me
for (int i = 0; i < count; i++) {
btn_title[i] = new Button(ActivityName.this);
btn_title[i].setText(menu.menu_title[i]);
btn_title[i].setId(i);
btn_title[i].setTextColor(Color.BLACK);
btn_title[i].setBackgroundColor(Color.parseColor(dataxml
.getMenucolor()));
btn_title[i]
.setTextSize(Integer.parseInt(dataxml.getFontsize()));
btn_title[i].setGravity(Gravity.CENTER_VERTICAL
| Gravity.CENTER_HORIZONTAL);
btn_title[i].setSingleLine();
btn_title[i].setEllipsize(TruncateAt.END);
btn_title[i].setOnClickListener(new ButtonListner());
}
hope this will help
why don't extend Button class, set its color, then use that new class?
It wont work obviously , let me explain why it has set last value of button .
you are using of one button reference (whatever u got from (Button)findViewById(R.id.btn_1) )
and untimely there is a one button reference and u just change its value using l.add(btn_1);
what you need to do is , do create a new button instance for each button and inflate it in proper view .
here is the small tick for that
for (int i==0 ; i < length; i++ ){
Button button = new Button(context);
collectionOfButton.add(button) ;
}
use that buttons collection using inflate if u try to integrate in some xml layout file .
I want to give ID to some views (textview ,imageview etc) in a layout that is programmetically created.
So what is the best way to set ID.
You create an ids.xml file and place all your required ids in it as below
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item type="id" name="layout1" />
<item type="id" name="layout2" />
<item type="id" name="layout3" />
</resources>
Now for your dynamically created layouts or views you can use these ids as below
new_layout1.setId(R.id.layout1);
new_view2.setId(R.id.layout2);
new_layout3.setId(R.id.layout3);
I hope it may help you.
Google finally realized the need of generating unique IDs for programmatically created views...
From API level 17 and above, one can use View.generateViewId() like this:
view.setId(View.generateViewId());
For apps targeting API level 16 or lower, use ViewCompat.generateViewId() instead:
view.setId(ViewCompat.generateViewId());
create folder res/values/ids.xmland
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item name="refresh" type="id"/>
<item name="settings" type="id"/>
</resources>
in Activity class call like this
ImageView refreshImg = new ImageView(activity);
ImageView settingsImg = new ImageView(activity);
refreshImg.setId(R.id.refresh);
settingsImg .setId(R.id.settings);
This wont work:
layout.setId(100);
But, this will:
int id=100;
layout.setId(id);
also, this one too (credit: Aaron Dougherty):
layout.setId(100+1);
For compatibility purposes use: ViewCompat.generateViewId()
If you are putting a group of components repeatedly into a layout programmatically like below:
<LinearLayout>
<ImageView>
<TextView>
<Button>
<ImageView>
<TextView>
<Button>
<ImageView>
<TextView>
<Button>
...
</LinearLayout>
then,you can use for loop and give ids accordingly:
for(int i=0;i<totalGroups;i++)
{
ImageView img;
TextView tv;
Button b;
... // set other properties of above components
img.setId(i);
tv.setId(i);
b.setId(i);
... //handle all events on these components here only
... //add all components to your main layout
}
Or if just one group of component you want to add,you can use any integer number which is large and don't conflict with other component's ids in Resources.It won't be much conflicting.
I went about it in a different way.
Created my own R.id HashMap.
Than used the value for the view.setID() part.
String is the id, Integer its value
Private HashMap<String, Integer> idMap= new HashMap<String, Integer>();
private int getRandomId(){
boolean notInGeneralResourses = false;
boolean foundInIdMap = false;
String packageName = mainActivity.getPackageName();
Random rnd = new Random();
String name ="";
//Repaet loop in case random number already exists
while(true) {
// Step 1 - generate a random id
int generated_id = rnd.nextInt(999999);
// Step 2 - Check R.id
try{
name = mainActivity.getResources().getResourceName(generated_id);
}catch(Exception e){
name = null;
}
notInGeneralResourses = false;
if (name == null || !name.startsWith(packageName)) {
notInGeneralResourses = true;
}else{
notInGeneralResourses = false;
localLog("Found in R.id list.");
}
// Step 3 - Check in id HashMap
if(notInGeneralResourses){
List<Integer> valueList = new ArrayList<Integer>(idMap.values());
foundInIdMap = false;
for (Integer value : valueList) {
if (generated_id == value) {
foundInIdMap = true;
localLog("Found in idMAp.");
}
}
}
// Step 4 - Return ID, or loop again.
if (!foundInIdMap) {
localLog("ID clear for use. "+generated_id);
return generated_id;
}
}
}
and to set:
String idName = "someName";
int generated_R_id = getRandomId();
idMap.put(idName,generated_R_id);
someView.setId(idMap.get(idName));
Now, at any point you can just:
ImageView test = (ImageView)
mainActivity.findViewById(idMap.get("somName"));
and to test it -
test.setImageResource(R.drawable.differentPic);
P.S. I've written it like this for ease of explain.
Obviously it can be written better andmore compact.
Try this code!
This should help give an idea.
activity_prac_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:text="#string/edit_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/display_txt"
android:textStyle="bold"
android:textSize="18sp"
android:textAlignment="center"
android:layout_gravity="center_horizontal"/>
<GridLayout
android:id="#+id/my_grid"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:rowCount="4">
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/linear_view">
<Button
android:text="#string/button_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/my_btn"
android:layout_gravity="center_horizontal"/>
<TextView
android:text="#string/edit_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/my_txt"
android:textSize="18sp"
/>
</LinearLayout>
</GridLayout>
</LinearLayout>
here's the rest of code
public class AnotherActivity extends AppCompatActivity {
private int count = 1;
List<Integer> gridArray;
private TextView myDisplayText;
#Override
protected void onCreate( Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
gridArray = new ArrayList<>();
gridArray.add(Integer.valueOf(1));
setContentView(R.layout.activity_prac_main);
findViews();
}
private void findViews(){
GridLayout gridLayout = (GridLayout)findViewById(R.id.my_grid);
gridLayout.setColumnCount(4);
LinearLayout linearLayout = (LinearLayout) gridLayout.findViewById(R.id.linear_view);
linearLayout.setTag("1");
Button myButton = (Button) linearLayout.findViewById(R.id.my_btn);
myButton.setTag("1");
TextView myText = (TextView) linearLayout.findViewById(R.id.my_txt);
myText.setText("1");
myDisplayText = (TextView) findViewById(R.id.display_txt);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TextView txt = (TextView) view;
myDisplayText.setText("PRESS " + txt.getTag().toString());
if(count < 24) {
createView();
}
else{
dialogBox();
}
}
});
}
private void createView(){
LinearLayout ll = new LinearLayout(this);
ll.setId(Integer.valueOf(R.id.new_view_id));
ll.setTag(String.valueOf(count+1));
Button newBtn = createButton();
newBtn.setId(Integer.valueOf(R.id.new_btn_id));
newBtn.setTag(String.valueOf(count+1));
TextView txtView = createText();
txtView.setId(Integer.valueOf(R.id.new_txt_id));
txtView.setTag(String.valueOf(count+1));
txtView.setText(String.valueOf(count+1));
GridLayout gridLayout = (GridLayout)findViewById(R.id.my_grid);
ll.addView(newBtn);
ll.addView(txtView);
ll.setOrientation(LinearLayout.VERTICAL);
gridLayout.addView(ll);
count++;
}
private Button createButton(){
Button myBtn = new Button(this);
myBtn.setText(R.string.button_send);
myBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TextView txt = (TextView) view;
myDisplayText.setText("PRESS " + txt.getTag().toString());
if(count < 24) {
createView();
}
else{
dialogBox();
}
}
});
return myBtn;
}
public void dialogBox() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("GRID IS FULL!");
alertDialogBuilder.setPositiveButton("DELETE",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
GridLayout gridLayout = (GridLayout)findViewById(R.id.my_grid);
gridLayout.removeAllViews();
count = 0;
createView();
}
});
alertDialogBuilder.setNegativeButton("CANCEL",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
private TextView createText(){
TextView myTxt = new TextView(this);
myTxt.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
return myTxt;
}
}
As you can see ids were created in res -> values -> ids file.
when creating views dynamically id is the same for the views.
Each TextView share same id. Each Button share same id. each layout share same id.
Ids are only important to access the contents of views.
However the Tag is what makes each view unique to each other.
Hope this helps you out!
All you need to do is call ViewCompat.generateViewId()
For Example:
val textView = TextView(this)
textView.text = "Hello World"
textView.setLayoutParams(ViewGroup.LayoutParams(MATCH_PARENT, WRAP_CONTENT))
textView.id = ViewCompat.generateViewId()
You can define your Ids as resources and then use setId() of the view to set it.
In a xml file, define the ID's like:
<resources>
<item type="id">your id name</item>
</resources>
then, use in the java file as..
layout.setId(R.id.<your id name>)
Looking for an example of how to dynamically add controls from the activity.
Inside an activity, lets call it "Activity2.cs", dynamically add a variable number of buttons to "MyView.axml".
I'm looking for code like below (except code that actually works):
string[] textArray = new string[] { "button1", "button2", "button3", "button4" };
int counter= 3;
for (int i = 0; i < length; i++)
{
var mytest = new button(this);
mytest.Text = textArray[i];
mytest.id= textArray[i];
View(MyView.axml).add(mytest);
}
The result would be that four buttons are added at the bottom of the view. I can find examples for how to dynamically add controls in Android, but not when using Mono for Android (ie in Visual Studio).
Let's say your layout file looks like this (Main.axml):
<?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"
android:id="#+id/Buttons">
</LinearLayout>
Then in your activity you can add Button objects to the layout like this:
[Activity(Label = "Buttons", MainLauncher = true, Icon = "#drawable/icon")]
public class ButtonActivity : Activity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
var buttons = FindViewById<LinearLayout>(Resource.Id.Buttons);
for (int i = 1; i <= 4; i++)
{
var button = new Button(this);
button.Text = "Button " + i;
button.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent,
ViewGroup.LayoutParams.WrapContent);
buttons.AddView(button);
}
}
}