I got the following code
for (int i = 0; i < cantcuenta ; i++) {
textview = new ArrayList<>();
final Integer nro = i + 1;
Hmayor = new LinearLayout(view.getContext());
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
param.weight = pesoLayout;
Hmayor.setOrientation(LinearLayout.VERTICAL);
Hmayor.setWeightSum(1);
Hmayor.setLayoutParams(param);
scrollview = new ScrollView(view.getContext());
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0);
params.weight = 0.65f;
scrollview.setLayoutParams(params);
linearinterno = new LinearLayout(view.getContext());
linearinterno.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
linearinterno.setOrientation(LinearLayout.VERTICAL);
scrollview.addView(linearinterno);
for (int j = 0; j < 10; j++)
{
test = new TextView(view.getContext());
test.setId(j);
test.setText("Lorem Ipsum" + j);
test.setVisibility(View.GONE);
textview.add(test);
}
boleta = new Button(view.getContext());
RelativeLayout.LayoutParams parambo = new RelativeLayout.LayoutParams(100, 50);
boleta.setLayoutParams(parambo);
boleta.setText("BOLETA");
boleta.setTextSize(TypedValue.COMPLEX_UNIT_SP, 10);
boleta.setTypeface(Typeface.DEFAULT_BOLD);
boleta.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
boleta.setTextColor(getResources().getColor(white, null));
boleta.setBackgroundColor(getResources().getColor(colorAccent, null));
boleta.setId(nro);
boleta.setPadding(0,0,0,0);
boleta.setVisibility(View.GONE);
boleta.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
factura = new Button(view.getContext());
RelativeLayout.LayoutParams paramfa = new RelativeLayout.LayoutParams(100, 50);
paramfa.addRule(RelativeLayout.RIGHT_OF, boleta.getId());
factura.setLayoutParams(paramfa);
factura.setText("FACTURA");
factura.setTextSize(TypedValue.COMPLEX_UNIT_SP, 10);
factura.setTypeface(Typeface.DEFAULT_BOLD);
factura.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
factura.setTextColor(getResources().getColor(white, null));
factura.setBackgroundColor(getResources().getColor(colorAccent, null));
factura.setPadding(0,0,0,0);
factura.setVisibility(View.GONE);
factura.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
ncuenta = new Button(view.getContext());
LinearLayout.LayoutParams paramb = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0);
paramb.weight = 0.15f;
ncuenta.setLayoutParams(paramb);
ncuenta.setPadding(0,0,0,0);
ncuenta.setText("CUENTA " + nro);
ncuenta.setTextSize(TypedValue.COMPLEX_UNIT_SP, 10);
ncuenta.setTypeface(Typeface.DEFAULT_BOLD);
ncuenta.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START);
ncuenta.setTextColor(getResources().getColor(letras, null));
ncuenta.setBackgroundColor(getResources().getColor(transparent, null));
ncuenta.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Boolean sw = false;
for (TextView este : textview)
{
if (este.getVisibility() == View.GONE)
{
este.setVisibility(View.VISIBLE);
linearinterno.addView(este);
factura.setVisibility(View.VISIBLE);
boleta.setVisibility(View.VISIBLE);
sw = true;
}
}
if (!sw)
{
for (TextView este : textview)
{
este.setVisibility(View.GONE);
factura.setVisibility(View.GONE);
boleta.setVisibility(View.GONE);
}
linearinterno.removeAllViews();
}
}
});
Hmayor.addView(ncuenta);
Hmayor.addView(scrollview);
linearinternodw = new LinearLayout(view.getContext());
LinearLayout.LayoutParams paramdw = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,0);
paramdw.weight = 0.2f;
linearinternodw.setLayoutParams(paramdw);
Hmayor.addView(linearinternodw);
relainterno = new RelativeLayout(view.getContext());
RelativeLayout.LayoutParams paramr = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
relainterno.setLayoutParams(paramr);
relainterno.addView(factura);
relainterno.addView(boleta);
linearinternodw.addView(relainterno);
theParent.addView(Hmayor);
}
it creates this distribution
when i press the button "CUENTA 1" with the name "ncuenta" in the code it should make all the text in the its own layout gone along with the buttons "BOLETA" and "FACTURA" also shown in the picture but instead, it makes it gone for the "CUENTA 2" views, I have done this kind of coding for recyclerviews and everything get instanced separatedly, would think that with a FOR everytime it does create a new instance of any view it would get attached to the corresponding cycle of the FOR.
if I divide the screen in 4 the first 3 buttons will show and hide the "CUENTA 4" wich tells me the the setOnclickListener its only taking the last set of items instanced..
Any ideas on how could solve this?
thanks in advance
Your onClickListener executes this code
for (TextView este : textview)
{
if (este.getVisibility() == View.GONE)
{
este.setVisibility(View.VISIBLE);
linearinterno.addView(este);
factura.setVisibility(View.VISIBLE);
boleta.setVisibility(View.VISIBLE);
sw = true;
}
}
When executed, the contents of the textview ArrayList will be the elements you add in the last iteration, that's why only the views in the last section are targeted.
Hope it helps.
I have linear layout R.id.linearLayoutQuantityPrice in XML.
I want to add a new linear layout inside that dynamically.
The new linear layout has two textviews and one imageview.
List<Price> priceList = database.getItemQuantityPrice(id);
LinearLayout linearLayoutQuantityPrice = (LinearLayout) rowView
.findViewById(R.id.linearLayoutQuantityPrice);
for (int i=0; i<priceList.size() ; i++) {
Price price = new Price();
price = priceList.get(i);
LinearLayout newLinearLayout = new LinearLayout(context);
newLinearLayout.setOrientation(LinearLayout.HORIZONTAL);
LayoutParams newLayoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
newLinearLayout.setPadding(2, 2, 2, 2);
newLinearLayout.setWeightSum(3);
int iqpId = price.getIqpId();
String quantityIn = price.getQuantityIn();
int quantity = price.getItmQnt();
int itemPrice = price.getItmPrc();
TextView tvQuantity=new TextView(context);
tvQuantity.setId(price.getIqpId()+10);
tvQuantity.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,1.0f));
tvQuantity.setTextSize(12);
if(quantityIn.equalsIgnoreCase("gm") && quantity>=1000){
quantity = quantity/1000;
quantityIn = new String("KG");
}
tvQuantity.setText(""+quantity+" "+quantityIn);
newLinearLayout.addView(tvQuantity);
TextView tvPrice=new TextView(context);
tvPrice.setId(price.getIqpId()+11);
tvPrice.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,1.0f));
tvPrice.setTextSize(12);
tvPrice.setText("Rs. "+itemPrice);
newLinearLayout.addView(tvPrice);
ImageView ivButton = new ImageView(context);
ivButton.setId(iqpId);
ivButton.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT, 1.0f));
ivButton.setImageDrawable(rowView.getResources().getDrawable(R.drawable.add_button));
ivButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int toCartId = v.getId();
Toast.makeText(context, "Added to cart" + toCartId, Toast.LENGTH_SHORT).show();
}
});
linearLayoutQuantityPrice.addView(newLinearLayout);
}
The code doesn't get any errors. But the desired views are not added.
Because you forgot to set the layout params.
newLinearLayout.setLayoutParams(newLayoutParams)
Try to use this. This is worked for me.
ArrayList<Component> components;
LinearLayout llRowContainer;
llRowContainer = (LinearLayout) findViewById(R.id.ll_row_container);
components = IappApp.getContext().getDBManager()
.getComponentList(COMPONENT_TYPE, ACTIVITY_TYPE);
int index = 0;
for (Component component : components) {
View rowView = View.inflate(this, R.layout.dae_general_info_row , null);
llRowContainer.addView(rowView);
final TextView txtViewTitle = (TextView) rowView
.findViewById(R.id.txtViewTitle);
final EditText editTextAns = (EditText) rowView
.findViewById(R.id.editTextAns);
editTextAns.setHint(component.getUnit()+"");
txtViewTitle.setText(++index + ". " + component.getTitle());
editTextAns.setTag(component);
}
I made a layout which contains radio button. I want to pass value of selected radio button to database so how can I get this value.?
Code is given below..Please help me..
private View drawRadioTypeQuestion(Question question, ArrayList<QuestionOption> questionOptions) {
LinearLayout layout = new LinearLayout(this);
layout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
layout.setOrientation(LinearLayout.VERTICAL);
layout.setPadding(5, 5, 5, 5);
TextView tv = new TextView(this);
tv.setText(question.Question_Order + ". " + question.Question_Title);
tv.setTextSize(16);
// tv.setTypeface(PhoneStatus.getRobotoMediumTypeface(this));
layout.addView(tv);
RadioGroup rg = new RadioGroup(this);
rg.setOrientation(RadioGroup.VERTICAL);
for (QuestionOption opt : questionOptions) {
RadioButton rb = new RadioButton(this);
rb.setText(opt.Question_Answer_Value);
rb.setTextSize(16);
rg.addView(rb);
}
layout.addView(rg);
PhoneStatus.overrideFonts(QuestionListActivity.this, layout);
tv.setTypeface(PhoneStatus.getRobotoMediumTypeface(this));
return layout;
}
try this code
rg.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
RadioButton rb = (RadioButton) findViewById(checkedId);
String value = rb.getText().toString();
}
});
Implement click listener on radio button. On onclick event add value of selected radio button to database..
Visit Here for official document
http://developer.android.com/guide/topics/ui/controls/radiobutton.html
and
http://android-er.blogspot.in/2009/11/radiogroup-and-radiobutton.html
i am creating a table layout with radio group by dynamically adding radiobuttons to it and i want to know which row is selected containing the radio group and i want to retrive the texview data also in the same row .how can i do that any suggestion will be a great help for me.
public class TabActivity extends Activity {
TableLayout table;
RadioGroup mRadioGroup;
ArrayList<String> list_name;
int color_blue = -16776961;
int color_gray = -7829368;
int color_black = -16777216;
int color_white = -1;
final int CHECK_BUTTON_ID = 982301;
int ids_check[];
boolean bool_check[];
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
table = (TableLayout) findViewById(R.id.tableLayout1);
list_name = new ArrayList<String>();
list_name.add("Close");
list_name.add("Cristiano");
list_name.add("David");
list_name.add("Fernando");
list_name.add("Messi");
list_name.add("Kaka");
list_name.add("Wayne");
list_name.add("use");
list_name.add("e");
list_name.add("eff");
list_name.add("euyr");
list_name.add("ejjyytuty");
list_name.add("madre");
list_name.add("yuir");
list_name.add("eyrty");
list_name.add("etytr");
list_name.add("ewrrtt");
bool_check = new boolean[list_name.size()];
ids_check = new int[list_name.size()];
createTableRows();
}
public void createTableRows()
{
for (int i = 0; i < list_name.size(); i++)
{
final TableRow table_row = new TableRow(this);
TextView tv_name = new TextView(this);
Button btn_check = new Button(this);
ImageView img_line = new ImageView(this);
table_row.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
table_row.setBackgroundColor(color_black);
table_row.setGravity(Gravity.CENTER_HORIZONTAL);
// table_row.setFocusable(true);
mRadioGroup = new RadioGroup(this);
// test adding a radio button programmatically
final RadioButton[] mbutton=new RadioButton[7];
for(int l=0;l<7;l++){
mbutton[l]=new RadioButton(this);
mbutton[l].setText("test"+l);
mRadioGroup.addView(mbutton[l]);
}
// LinearLayout.LayoutParams layoutParams = new RadioGroup.LayoutParams(
// RadioGroup.LayoutParams.WRAP_CONTENT,
// RadioGroup.LayoutParams.WRAP_CONTENT);
// mRadioGroup.addView(newRadioButton);
tv_name.setText((CharSequence) list_name.get(i));
tv_name.setTextColor(color_blue);
tv_name.setTextSize(30);
tv_name.setTypeface(Typeface.DEFAULT_BOLD);
tv_name.setWidth(150);
btn_check.setLayoutParams(new LayoutParams(30, 30));
btn_check.setBackgroundResource(R.drawable.small_checkbox_unchecked);
img_line.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 2));
img_line.setBackgroundResource(R.drawable.separater_line);
table_row.addView(tv_name);
table_row.addView(btn_check);
table_row.addView(mRadioGroup);
table.addView(table_row);
table.addView(img_line);
//table.addView(mRadioGroup);
mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup mRadioGroup, int checkedId) {
for(int i=0; i<mRadioGroup.getChildCount(); i++) {
RadioButton btn = (RadioButton) mRadioGroup.getChildAt(i);
int t=table.indexOfChild(table_row);
System.out.println(t);
if(btn.getId() == checkedId) {
String text = btn.getText().toString();
// do something with text
Log.d(text," event1");
return;
}
}
}
});
}
}
}
Why are you not using ListView ? there's nothing in the code that cannot be done by a list view?
You can add you layout by setting the custom adapter.
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);