I want to add buttons dynamically. I am adding multiple buttons dynamically but I want to add the buttons in following pattern:
[BUTTON1] [BUTTON2]
[BUTTON3] [BUTTON4]
[BUTTON5] [BUTTON6]
That means I want to add only 2 buttons in a row that is dynamically.
I have tried many options.
one of them is:
LinearLayout ll = (LinearLayout) findViewById(R.id.buttonlayout);
Button[][] buttonArray = new Button[count][count];
TableLayout table = new TableLayout(this);
for (int row = 0; row < count; row++) {
TableRow currentRow = new TableRow(this);
for (int button = 0; button < row; button++) {
Button currentButton = new Button(this);
// you could initialize them here
currentButton.setOnClickListener(this);
// you can store them
buttonArray[row][button] = currentButton;
// and you have to add them to the TableRow
currentRow.addView(currentButton);
}
// a new row has been constructed -> add to table
table.addView(currentRow);
}
and finally takes that new table and add it to your layout. ll.addView(table);
Note: count of button could be random.
How can I do that?
Use vertical LinearLayout in XML. Then programmatically create horizontal LinearLayout and add buttons in horizontal layout. For each line, create and add new horizontal layout.
XML:
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/buttonlayout">
</LinearLayout>
ACTIVITY:
public class dynamicButtons extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myLayout);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
int numberOfRows = 3;
int numberOfButtonsPerRow = 2;
int buttonIdNumber = 0;
final LinearLayout verticalLayout= LinearLayout)findViewById(R.id.buttonlayout);
for(int i=0;i<numberOfRows;i++){
LinearLayout newLine = new LinearLayout(this);
newLine.setLayoutParams(params);
newLine.setOrientation(LinearLayout.HORIZONTAL);
for(int j=0;j<numberOfButtonsPerRow;j++){
Button button=new Button(this);
// You can set button parameters here:
button.setWidth(20);
button.setId(buttonIdNumber);
button.setLayoutParams(params);
button.setText("Button Name");
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent is = new Intent(getApplicationContext(), someOtherApplication.class);
is.putExtra("buttonVariable", buttonIdNumber);
startActivity(is);
}
});
newLine.addView(button);
buttonIdNumber++;
}
verticalLayout.addView(newLine);
}
}
}
try this code:
TableLayout layout = new TableLayout (this);
layout.setLayoutParams( new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT));
for (int i=0; i<2; i++) { //number of rows
TableRow tr = new TableRow(this);
for (int j=0; j<2; j++) { //number of columns
Button b = new Button (this);
b.setText("Button:"+i+j);
b.setTextSize(10.0f);
b.setOnClickListener(this);
tr.addView(b, 30,30);
}
layout.addView(tr);
}
As your number of button is random u can use:
int total = 20; //random number of buttons
int column = 3; //specify the column number
int row = total / column;
now use the column and row value to dynamically show buttons
Do something like this:
LinearLayout ll_Main = new LinearLayout(getActivity());
LinearLayout ll_Row01 = new LinearLayout(getActivity());
LinearLayout ll_Row02 = new LinearLayout(getActivity());
ll_Main.setOrientation(LinearLayout.VERTICAL);
ll_Row01.setOrientation(LinearLayout.HORIZONTAL);
ll_Row02.setOrientation(LinearLayout.HORIZONTAL);
final Button button01 = new Button(getActivity());
final Button button02 = new Button(getActivity());
final Button button03 = new Button(getActivity());
final Button button04 = new Button(getActivity());
ll_Row01.addView(button01);
ll_Row01.addView(button02);
ll_Row02.addView(button03);
ll_Row02.addView(button04);
ll_Main.addView(ll_Row01);
ll_Main.addView(ll_Row02);
button04.setVisibility(View.INVISIBLE);
button04.setVisibility(View.VISIBLE);
Create a listview/recyclerview with custom item that hold 2 button as you mentioned in your question, than populate that listView with the buttons (inside the adapter if item index % 2 == 0 it will take the left position otherwise the right position).
This my code what I have written :
while (i.hasNext()){
Map.Entry me= (Map.Entry) i.next();
checkBox=new CheckBox(this.getActivity());
checkBox.setId(Integer.parseInt(me.getKey().toString()));
checkBox.setText(me.getValue().toString());
checkBox.setOnClickListener(getOnClickDoSomething(checkBox));
LinearLayout.LayoutParams params= (LinearLayout.LayoutParams) linearMain.getLayoutParams();
params.width=250;
linearMain.addView(checkBox);
dltButton=new Button(this.getActivity());
dltButton.setTag(btnCounter);
btnCounter++;
dltButton.setText("Delete");
linearMain.addView(dltButton);
}
and the screen is like this.
I want one check box and one delete button side by side and next in the next row similar way.
How to implement it any idea?
ok try this, Ihave modified your code to basic logic.you Activity's layout file should be as follows
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/mainContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
</LinearLayout >
and then you activity should be
public class MainActivity extends AppCompatActivity {
LinearLayout mainContainer;
CheckBox checkBox;
Button dltButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainContainer = (LinearLayout) findViewById(R.id.mainContainer);
for (int i = 0; i < 5 ; i++){
checkBox=new CheckBox(this);
checkBox.setText("Text");
LinearLayout linearMain = new LinearLayout(this);
linearMain.setOrientation(LinearLayout.HORIZONTAL);
linearMain.setWeightSum(1.0f);
LinearLayout.LayoutParams half = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT, 0.5f);
linearMain.addView(checkBox, half);
dltButton=new Button(this);
dltButton.setTag("tag");
dltButton.setText("ffff");
linearMain.addView(dltButton, half);
mainContainer.addView(linearMain);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout layout = (LinearLayout) findViewById(R.id.linear_layout);
layout.setOrientation(LinearLayout.VERTICAL);
String[] count = new String[] { "1", "2", "3" };
int checkbox_count = 3;
CheckBox checkBox;
for (int i = 0; i < checkbox_count; i++) {
LinearLayout horizontal_layout = new LinearLayout(this);
horizontal_layout.setOrientation(LinearLayout.HORIZONTAL);
horizontal_layout.setLayoutParams(new LinearLayout.LayoutParams(500, 80));
checkBox = new CheckBox(this);
checkBox.setText("checkbox " + count[i]);
horizontal_layout.addView(checkBox);
Button delete_btn = new Button(this);
delete_btn.setText("Delete");
horizontal_layout.addView(delete_btn);
layout.addView(horizontal_layout);
}
}
In this code I'm building a method that adds the same image a number of times to a Relative Layout at runtime. However, the images are not showing up when debugging. The textview that was added is acting normally. Can someone explain how to make the images visible? Thanks in advance.
My Code:
public class TestActivity extends Activity {
ArrayClass arraysObject1 = new ArrayClass();
ArrayList<ImageView> mImages = new ArrayList<ImageView>();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
RelativeLayout layout = new RelativeLayout(this);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
layout.setLayoutParams(params);
layout.setBackgroundColor(Color.parseColor("#FFFFFF"));
//textview is working
TextView testText = new TextView(this);
testText.setText("Alle aangeboden vacatures vindt u hieronder terug.");
testText.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
layout.addView(testText);
RelativeLayout.LayoutParams imgParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
imgParams.addRule(RelativeLayout.CENTER_IN_PARENT);
for(int i=0; i<arraysObject1.array1.size(); i++)
{
mImages.add(new ImageView(this));
mImages.get(i).setVisibility(View.VISIBLE);
mImages.get(i).setBackgroundResource(R.drawable.work);
mImages.get(i).setLayoutParams(imgParams);
layout.addView(mImages.get(i));
}
setContentView(layout);
}
}
Your cycle for(int i=0; i < arraysObject1.array1.size(); i++) seemed not to be executed.
arraysObject1.array1 is empty.
I have a weird problem. I derived MessageRow from TableRow. I populated a table with one TableRow (Header) and 100 MessageRows. But when I add the table to the HorizontalScroll view only the Messagerows are showing.
If I inspect the table in the debugger, all the rows are there, including the Header, with the right children and text.
This is the simplified code:
public class MessageRow extends TableRow {
public TextView tvData1;
public TextView tvData2;
public TextView tvData3;
public MessageRow(Context context) {
this(context, null);
}
public MessageRow(Context context, AttributeSet attrs) {
super(context, attrs);
tvData1 = new TextView(context);
tvData2 = new TextView(context);
tvData3 = new TextView(context);
}
public void setData(String data1, String data2, String data3) {
tvData1.setText(data1);
tvData2.setText(data2);
tvData3.setText(data3);
addView(tvData1);
addView(tvData2);
addView(tvData3);
}
}
The activity code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.viewer);
mTable = new TableLayout(this);
HorizontalScrollView hview = (HorizontalScrollView) findViewById(R.id.hscroll);
mTable.setBackgroundColor(Color.WHITE);
populate(mTable);
hview.addView(mTable);
}
public void setHeader(TableLayout tl) {
TableRow mHeader = new TableRow(getContext());
mHeader.addView(getColumnHeader("Data#1"));
mHeader.addView(getColumnHeader("Data#2"));
mHeader.addView(getColumnHeader("Data#3"));
mHeader.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
tl.addView(mHeader);
}
public void populate(TableLayout tl) {
setHeader(tl);
for(int i = 0; i < 100; i++) {
MessageRow mr = new MessageRow(getContext());
mr.setMessage("xxx"+i,"yyy"+i,"zzz"+i);
mr.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
tl.addView(mr);
}
}
private Button getColumnHeader(String name) {
Button bt = new Button(getContext());
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.rightMargin = params.leftMargin = 2;
bt.setLayoutParams(params);
bt.setText(name);
return bt;
}
Now, I tried bypassing the getColumnHeader() function like this:
public void setHeader(TableLayout tl) {
TableRow mHeader = new TableRow(getContext());
//mHeader.addView(getColumnHeader("Data#1"));
--> Button bt1 = new Button(getContext());
--> bt1.setText("Data#1");
--> mHeader.addView(bt1);
//mHeader.addView(getColumnHeader("Data#2"));
--> Button bt2 = getColumnHeader("Data#2");
--> mHeader.addView(bt2);
mHeader.addView(getColumnHeader("Data#3"));
mHeader.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
tl.addView(mHeader);
}
and then bt1 (Data#1) is displayed!!! but not Data#2 or Data#3. This hints that somehow the function getColumnHeader() is bad. But not acording to the debugger, when I inspect bt1 and bt2 they seem good, I cannot detect what is the difference between the manually instantiated button bt1 and the returned button bt2.
Side note: I don't know if this is the best way, but to compare the two variables I just right-clicked and Copy Variable, then pasted it to notepad++ in two different files (one for bt1 and one for bt2) and used the compare plugin.
Some more info. I managed to display the buttons, further debug showed that setting the Layout params for each button in the function getColumnHeader() caused the problem. Still I don't know why.
The button member mLayoutParams being null is OK, but when created (.setLAyoutParams()) and assigned values (for example width and height) the suddenly the button is not displayed.
This is the patch,... until I figure out why.
private Button getColumnHeader(String name) {
Button bt = new Button(getContext());
//LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
//params.rightMargin = params.leftMargin = 2;
//bt.setLayoutParams(params);
bt.setText(name);
return bt;
}
Last piece of the puzzle.
I tried many variations and finally it worked!
Replacing LayoutParams with TableRow.LayoutParams did the trick.
Their structure is very similar, probably even TableRow.LayoutParams is derived from LayoutParams.
I will leave the mystery here, until some expert sheds light on why this happened.
The final code:
private Button getColumnHeader(String name) {
Button bt = new Button(getContext());
TableRow.LayoutParams params = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.MATCH_PARENT);
params.rightMargin = params.leftMargin = 2;
bt.setLayoutParams(params);
bt.setText(name);
return bt;
}
How to add a button dynamically in Android?
Button myButton = new Button(this);
myButton.setText("Push Me");
LinearLayout ll = (LinearLayout)findViewById(R.id.buttonlayout);
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
ll.addView(myButton, lp);
Have a look to this example
try this:
for (int i = 1; i <= 20; i++) {
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
Button btn = new Button(this);
btn.setId(i);
final int id_ = btn.getId();
btn.setText("button " + id_);
btn.setBackgroundColor(Color.rgb(70, 80, 90));
linear.addView(btn, params);
btn1 = ((Button) findViewById(id_));
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Toast.makeText(view.getContext(),
"Button clicked index = " + id_, Toast.LENGTH_SHORT)
.show();
}
});
}
Try this:
LinearLayout ll = (LinearLayout)findViewById(R.id.layout);
Button btn = new Button(this);
btn.setText("Manual Add");
btn.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
ll.addView(btn);
for (int k = 1; k < 100; k++) {
TableRow row = new TableRow(this);
innerloop:
for (int l = 1; l < 4; l++) {
btn = new Button(this);
TableRow.LayoutParams tr = new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
layout.setWeightSum(12.0f);
tr.weight = 0;
btn.setLayoutParams(tr);
btn.setTextColor(a);
btn.setHeight(150);
btn.setWidth(150);
btn.setId(idb);
btn.setText("Button " + idb);
row.addView(btn);
}
}
try this
private void createLayoutDynamically(int n) {
for (int i = 0; i < n; i++) {
Button myButton = new Button(this);
myButton.setText("Button :"+i);
myButton.setId(i);
final int id_ = myButton.getId();
LinearLayout layout = (LinearLayout) findViewById(R.id.myDynamicLayout);
layout.addView(myButton);
myButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Toast.makeText(DynamicLayout.this,
"Button clicked index = " + id_, Toast.LENGTH_SHORT)
.show();
}
});
}
Try this code
Button btn=new Button(this);
btn.setId(btn);
btn.setBackgroundResource(R.drawable.image);
btn.setMinimumHeight(150);
btn.setMinimumWidth(150);
Relativelayout.addView(btn);
Check this up.
LinearLayout ll_Main = new LinearLayout(getActivity());
LinearLayout ll_Row01 = new LinearLayout(getActivity());
LinearLayout ll_Row02 = new LinearLayout(getActivity());
ll_Main.setOrientation(LinearLayout.VERTICAL);
ll_Row01.setOrientation(LinearLayout.HORIZONTAL);
ll_Row02.setOrientation(LinearLayout.HORIZONTAL);
final Button button01 = new Button(getActivity());
final Button button02 = new Button(getActivity());
final Button button03 = new Button(getActivity());
final Button button04 = new Button(getActivity());
ll_Row01.addView(button01);
ll_Row01.addView(button02);
ll_Row02.addView(button03);
ll_Row02.addView(button04);
ll_Main.addView(ll_Row01);
ll_Main.addView(ll_Row02);
button04.setVisibility(View.INVISIBLE);
button04.setVisibility(View.VISIBLE);
Button btn = new Button(this);
btn.setText("Submit");
LinearLayout linearLayout = (LinearLayout)findViewById(R.id.buttonlayout);
LayoutParams buttonlayout = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
linearLayout.addView(btn, buttonlayout);
Try this code. It will work fine..
public class DynamicViewsActivity extends Activity {
Button button;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_dynamic_views);
ScrollView scrl=new ScrollView(this);
final LinearLayout ll=new LinearLayout(this);
ll.setOrientation(LinearLayout.HORIZONTAL);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(100, 500, 100, 200);
scrl.addView(ll);
Button add_btn=new Button(this);
add_btn.setText("Click Here");
ll.addView(add_btn, layoutParams);
final Context context = this;
add_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(context, App2Activity.class);
startActivity(intent);
}
});
this.setContentView(scrl);
}
}
Try following code.
LinearLayout layout = (LinearLayout) findViewById(R.id.llayout);
layout.setOrientation(LinearLayout.VERTICAL);
Button btn = new Button(this);
btn.setText("Button1");
layout.add(btn);
btn = new Button(this);
btn.setText(Button2);
layout.add(btn);
like this you add Buttons as per your requirements.
public void add_btn() {
lin_btn.setWeightSum(3f);
for (int j = 0; j < 3; j++) {
LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params1.setMargins(10, 0, 0, 10);
params1.weight = 1.0f;
LinearLayout ll;
ll = new LinearLayout(this);
ll.setGravity(Gravity.CENTER_VERTICAL);
ll.setOrientation(LinearLayout.HORIZONTAL);
ll.setLayoutParams(params1);
final Button btn;
btn = new Button(DynamicActivity.this);
btn.setText("A"+(j+1));
btn.setTextSize(15);
btn.setId(j);
btn.setPadding(10, 8, 10, 10);
ll.addView(btn);
lin_btn.addView(ll);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(v.getId()==0)
{
txt_text.setText("Hii");
}else if(v.getId()==1)
{
txt_text.setText("hello");
}else if(v.getId()==2)
{
txt_text.setText("how r u");
}
}
});
}
}
Actually I add to the xml layout file anything that could be used! Then from the source code of the specific Activity I get the object by its id and I "play" with the visibility method.
Here is an example:
((Spinner)findViewById(R.id.email_spinner)).setVisibility(View.GONE);
I've used this (or very similar) code to add several TextViews to a LinearLayout:
// Quick & dirty pre-made list of text labels...
String names[] = {"alpha", "beta", "gamma", "delta", "epsilon"};
int namesLength = 5;
// Create a LayoutParams...
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.FILL_PARENT);
// Get existing UI containers...
LinearLayout nameButtons = (LinearLayout) view.findViewById(R.id.name_buttons);
TextView label = (TextView) view.findViewById(R.id.master_label);
TextView tv;
for (int i = 0; i < namesLength; i++) {
// Grab the name for this "button"
final String name = names[i];
tv = new TextView(context);
tv.setText(name);
// TextViews CAN have OnClickListeners
tv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
label.setText("Clicked button for " + name);
}
});
nameButtons.addView(tv, params);
}
The main difference between this and dicklaw795's code is it doesn't set() and re-get() the ID for each TextView--I found it unnecessary, although I may need it to later identify each button in a common handler routine (e.g. one called by onClick() for each TextView).
Button myButton = new Button(this);
myButton.setId(123);
myButton.setText("Push Me");
LinearLayout ll = (LinearLayout)findViewById(R.id.buttonlayout);
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
ll.addView(myButton, lp);
myButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Toast.makeText(DynamicLayout.this,
"Button clicked index = " + id_, Toast.LENGTH_SHORT)
.show();
}
});
If you want to add dynamically buttons try this:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
for (int i = 1; i <= 5; i++) {
LinearLayout layout = (LinearLayout) findViewById(R.id.myLinearLayout);
layout.setOrientation(LinearLayout.VERTICAL);
Button btn = new Button(this);
btn.setText(" ");
layout.addView(btn);
}
}
You could create a base layout for your button and dynamically change only what is specific, like this project I made to run different exercises from a Material Design course I'm taking:
In this example, I use a preconfigured AppCompatButton:
layout_base_button.xml
<android.support.v7.widget.AppCompatButton
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/btn_base"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="8dp"
style="#style/RaisedButton"
>
</android.support.v7.widget.AppCompatButton>
<style name="RaisedButton" parent="Widget.AppCompat.Button.Colored">
<item name="android:textSize">11sp</item>
<item name="android:textStyle">bold</item>
</style>
And in the MainActivity I created some instances and changed what I need, like the button text and onClick event:
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="udemy.android.materialdesign.MainActivity">
<LinearLayout
android:id="#+id/base_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
</LinearLayout>
</ScrollView>
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout baseLayout = findViewById(R.id.base_layout);
baseLayout.addView(createButton("TextFields", baseLayout,
view -> startActivity(createIntent(TextFieldsActivity.class))
));
baseLayout.addView(createButton("Buttons", baseLayout,
view -> startActivity(createIntent(ButtonsActivity.class))
));
baseLayout.addView(createButton("Toolbar", baseLayout,
view -> startActivity(createIntent(ToolbarActivity.class))
));
}
private View createButton(String text, LinearLayout baseLayout, View.OnClickListener onClickEvent) {
View inflated = LayoutInflater.from(this).inflate(R.layout.layout_base_button, baseLayout, false);
AppCompatButton btnBase = inflated.findViewById(R.id.btn_base);
btnBase.setText(text);
btnBase.setOnClickListener(onClickEvent);
return btnBase;
}
private Intent createIntent(Class<?> cls) {
return new Intent(this, cls);
}
}
Sorry for being late...
I needed to create buttons even more dynamically, not just in runtime but by pressing another button. So clicking this button will dynamically create more buttons under it. I recommend having a ScrollView on the activity or limit the number of clicks - so no buttons go offscreen.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteY="675dp">
<LinearLayout
android:id="#+id/layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Button
android:id="#+id/newItemButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button1" />
</LinearLayout>
</ScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout ll = (LinearLayout)findViewById(R.id.layout); //Screen layout
LinearLayout.LayoutParams params = new
LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
final Button newItemButton = findViewById(R.id.newItemButton);
newItemButton.setText("Create new button");
newItemButton.setOnClickListener(new View.OnClickListener() {
int pressCount = 1; //Count how many times button was pressed
public void onClick(View v) {
newItemButton.setText("Button Clicked: "+pressCount);
createButton(pressCount, params, ll); //Click to create new button
pressCount++;
}
});
} //end of onCreate
public void createButton(int id, LinearLayout.LayoutParams inputParams, LinearLayout inputLL) {
Button outButton = new Button(this);
outButton.setId(id);
final int id_ = outButton.getId();
outButton.setText("Button " + id_);
inputLL.addView(outButton, inputParams);
}
}//end of AppCompatActivity
This will give you an activity with a button.
When you click on that button, you spawn a new button underneath it.
If you spawn so many that they do not fit on the screen, the scrollView will take care of that.
In mainactivity.xml write:
<Button
android:id="#+id/search"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search"
android:visibility="invisible"/>
In main.java write:
Button buttonSearch;
buttonSearch = (Button)findViewById(R.id.search);
buttonSearch.setVisibility(View.VISIBLE);