Add Button to a Layout Programmatically

How do I programmatically add buttons into layout one by one in several lines?

The issue is that your buttons are not going to automatically wrap to the next part of the screen. You have to specifically tell Android how you want your Views to be positioned. You do this using ViewGroups such as LinearLayout or RelativeLayout.

LinearLayout layout = (LinearLayout) findViewById(R.id.linear_layout_tags);
layout.setOrientation(LinearLayout.VERTICAL); //Can also be done in xml by android:orientation="vertical"

for (int i = 0; i < 3; i++) {
LinearLayout row = new LinearLayout(this);
row.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));

for (int j = 0; j < 4; j++) {
Button btnTag = new Button(this);
btnTag.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
btnTag.setText("Button " + (j + 1 + (i * 4)));
btnTag.setId(j + 1 + (i * 4));
row.addView(btnTag);
}

layout.addView(row);
}

I'm assuming that R.id.linear_layout_tags is the parent LinearLayout of your XML for this activity.

Basically what you're doing here is you're creating a LinearLayout that will be a row to hold your four buttons. Then the buttons are added and are each assigned a number incrementally as their id. Once all of the buttons are added, the row is added to your activity's layout. Then it repeats. This is just some pseudo code but it will probably work.

Oh and next time be sure to spend more time on your question...

https://stackoverflow.com/questions/how-to-ask

Add button to a layout programmatically

This line:

layout = (LinearLayout) findViewById(R.id.statsviewlayout);

Looks for the "statsviewlayout" id in your current 'contentview'. Now you've set that here:

setContentView(new GraphTemperature(getApplicationContext()));

And i'm guessing that new "graphTemperature" does not set anything with that id.

It's a common mistake to think you can just find any view with findViewById. You can only find a view that is in the XML (or appointed by code and given an id).

The nullpointer will be thrown because the layout you're looking for isn't found, so

layout.addView(buyButton);

Throws that exception.

addition:
Now if you want to get that view from an XML, you should use an inflater:

layout = (LinearLayout) View.inflate(this, R.layout.yourXMLYouWantToLoad, null);

assuming that you have your linearlayout in a file called "yourXMLYouWantToLoad.xml"

Programmatically add button based on existing layout

See this similar question with answer.

Try this:

Button btn = (Button) inflater.inflate(R.layout.btn, layout, false);

Android - How to add buttons programmatically depending on screen size and button below each other dynamically?

Your buttons overlapped each others because your layout params is not appropriate:

params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
b.setLayoutParams(params);
b.setText("Bouton n°" + numBoutton);

With above code, all the buttons will align left with parent.

If you want to add buttons next to others, you should better use LinearLayout instead of RelativeLayout.

Suppose that you already have a linear layout with horizontal orientation.

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
b.setLayoutParams(params);
b.setText("Bouton n°" + numBoutton);
mainLinearLayout.addView(b);
numBoutton++;

That's all.

Edit: Here are some code, dont know if this is your need or not.

In this app, i have a LinearLayout inside a ScrollView and a Button. When i click the Button, i add new button to the ScrollView.

The MainActivity.java

package com.tiennt.myapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;

public class MainActivity extends AppCompatActivity {

private LinearLayout llButtons;
private int buttonCount;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Button btnAdd = (Button) findViewById(R.id.btn_add);
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
doAddButton();
}
});
llButtons = (LinearLayout) findViewById(R.id.ll_buttons);
}

private void doAddButton() {
Button button = new Button(this);
button.setText("Button " + ++buttonCount);
button.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
llButtons.addView(button);
}
}

The activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.tiennt.myapplication.MainActivity">

<Button
android:id="@+id/btn_add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ADD BUTTON"
android:layout_gravity="center_horizontal" />

<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">

<LinearLayout
android:id="@+id/ll_buttons"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" />

</ScrollView>

</LinearLayout>

Here are the result:
Result

Remove layout on a button click programmatically in android studio

Using RecyclerView with Adapter is your best bet in these situations. My working code is as followes

Class listAdapter

package com.akshita.recycler;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;

public class listAdapter extends RecyclerView.Adapter<listAdapter.ViewHolder> {
private ArrayList<String> product_name;
private ArrayList<Integer> quantity;
private ArrayList<Double> price;
private ArrayList<String> specs;
private static Context scontext;

public listAdapter(Context context)
{
scontext = context;
this.product_name = new ArrayList<String>();
this.price = new ArrayList<Double>();
this.quantity = new ArrayList<Integer>();
this.specs = new ArrayList<String>();
}

public listAdapter(Context context, ArrayList<String> pdname, ArrayList<Integer> quantity, ArrayList<Double> price, ArrayList<String> specs)
{
this.product_name = pdname;
this.price = price;
this.quantity = quantity;
this.specs = specs;
scontext = context;
}

@NonNull
@Override
public listAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View listItem = layoutInflater.inflate(R.layout.productview,parent,false);
ViewHolder viewHolder = new ViewHolder(listItem);
return viewHolder;
}

@Override
public void onBindViewHolder(@NonNull listAdapter.ViewHolder holder, int position) {
holder.actv.setText(product_name.get(position));
holder.qty.setText(quantity.get(position).toString());
holder.price.setText(price.get(position).toString());
holder.desc.setText(specs.get(position));

}
public void addView(String pdname, Double prc, Integer quant, String spec ) {

product_name.add(pdname);
quantity.add(quant);
price.add(prc);
specs.add(spec);
notifyItemInserted(product_name.size());
notifyItemInserted(quantity.size());
notifyItemInserted(price.size());
notifyItemInserted(specs.size());
}

public void removeAt(int position) {

product_name.remove(position);
quantity.remove(position);
price.remove(position);
specs.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, product_name.size());
notifyItemRangeChanged(position, quantity.size());
notifyItemRangeChanged(position, price.size());
notifyItemRangeChanged(position, specs.size());
}

@Override
public int getItemCount() {
return product_name.size();
}

public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public AutoCompleteTextView actv;
public EditText qty;
public EditText price;
public EditText desc;
public Button button;
public ViewHolder(View itemView) {
super(itemView);
this.actv = itemView.findViewById(R.id.tv_product);
this.qty = itemView.findViewById(R.id.prod_qty);
this.price = itemView.findViewById(R.id.prod_price);
this.desc = itemView.findViewById(R.id.prod_specs);
this.button = itemView.findViewById(R.id.btn_rmv);
button.setOnClickListener(this);
}

@Override
public void onClick(View v) {
if(v.equals(button)){
removeAt(getAdapterPosition());
}

}
}
}

My Main Class

MainActivity.java

package com.akshita.recycler;

import android.os.Bundle;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
listAdapter adapter;
RecyclerView hs;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
hs = findViewById(R.id.rcview);

hs.setHasFixedSize(false);
hs.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
}

@Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.add: addView(v);
}
}

public void addView(View v)
{
if(adapter == null) {
adapter = new listAdapter(this);
hs.setAdapter(adapter);
}
adapter.addView("Name",0.0, 0, "Specs");
}
}

productview.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:id="@+id/ll_out"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="5sp">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10sp"
android:orientation="horizontal">

<AutoCompleteTextView
android:id="@+id/tv_product"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="left|center_vertical"
android:gravity="left"
android:hint="Enter Product"
android:inputType="text" />
</LinearLayout>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10sp"
android:orientation="horizontal">
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".5"
android:orientation="vertical">

<EditText
android:id="@+id/prod_qty"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:editable="false"
android:focusable="true"
android:focusableInTouchMode="true"
android:hint="Enter Quantity"
android:gravity="left"
android:inputType="number" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".5"
android:orientation="vertical">
<EditText
android:id="@+id/prod_price"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:editable="false"
android:focusable="false"
android:focusableInTouchMode="false"
android:hint="Prod Price"
android:gravity="left"
android:inputType="none" />
</LinearLayout>

<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".5"
android:orientation="vertical">

<EditText
android:id="@+id/prod_specs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:editable="false"
android:focusable="false"
android:focusableInTouchMode="false"
android:gravity="left"
android:hint="Prod Specs"
android:inputType="none" />

</LinearLayout>

</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="1dp"
android:layout_marginTop="1dp"
android:padding="0dp">

<Button
android:id="@+id/btn_rmv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Remove Product"
android:textColor="@color/white" />
</LinearLayout>
</LinearLayout>
</LinearLayout>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:gravity="center|top"
android:orientation="vertical">
<Button
android:id="@+id/add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="addView"
/>
<androidx.recyclerview.widget.RecyclerView
android:layout_marginTop="10dp"
android:id="@+id/rcview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>

Whole working code is available here on GitHub

how to add buttons programmatically in android

For your case i want to suggest you to use Flow from constraintLayout instead of RelativeLayout. You can learn more by reading this article.



Related Topics



Leave a reply



Submit