Android: Adding buttons at runtime - android

I'm trying to add some buttons in my TableRow, at runtime. My TableRow has this structure:
<TableRow
android:layout_marginTop="100px"
android:gravity="bottom"
android:paddingTop="50px"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/riga1">
<Button
android:textSize="32px"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/buttonOK2"
android:text="YES"
android:onClick="setResult"/>
</TableRow>
And my java code is:
TableRow tr = (TableRow) findViewById(R.id.riga1);
Button b = new Button(this);
b.setText("button 1");
b.setId(1);
b.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
tr.addView(b);
Button b1 = new Button(this);
b1.setText("button 2");
b1.setId(2);
b1.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
tr.addView(b1);
But this seems not to work. In my activity I can see only the button defined in the xml file.
Another problem is that if I set in the related TableLayout the parameter:
android:stretchColumns="*"
I must insert (in xml file) at least one button in the TableRow of the aforementioned TableLayout, otherwise I obtain a "division by zero error" near streatchColumns What can I do, in order to let the tableRow empty?

I think that your problem is that you are using the wrong LayoutParams object for your TextViews try this:
TableRow.LayoutParams layoutParams = new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT);
and then set this layoutParams object:
b.setLayoutParams(layoutParams);

Instead of table layout you should use relative layout it's work for me try it
In Your XML File Like this
<RelativeLayout 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:id="#+id/myMainRelativeLayout"
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=".MainActivity" >
<Button
android:id="#+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="47dp"
android:text="Add Button" />
And your java code like bellow
public class MainActivity extends Activity implements
android.view.View.OnClickListener {
Button btnAdd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnAdd = (Button) findViewById(R.id.btnAdd);
btnAdd.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.btnAdd) {
RelativeLayout rl = (RelativeLayout)findViewById(R.id.myMainRelativeLayout);
Button btn = new Button(this);
btn.setId(1234);
btn.setText("Add Button Runtime");
btn.setOnClickListener(this);
rl.addView(btn);
}
if(v.getId() == 1234)
{
Toast.makeText(getApplicationContext(), "This is Your New Button", Toast.LENGTH_LONG).show();
}
}
}
try this one it's really work

first you need to find the button using this statement
btn=(Button)findViewById(R.id.Button1);
than you can set the visibility using this:
btn.setVisibility(View.INVISIBLE);
Then you can set the Visibility using the statement:
btn.setVisibility(View.VISIBLE);

Related

Dynamically add buttons to an already existing array of buttons

I am trying to create a button for each year since the person started using my app. So in my xml document I have
<HorizontalScrollView
android:id="#+id/yearScrollView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/white"
android:layout_gravity="center">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/currentYear"
android:tag="01"
android:text="2015"
android:paddingLeft="8.0dip"
android:paddingRight="8.0dip"
android:height="24dp"
android:textSize="18sp"
android:textColor="#333333"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/white"
>
</Button>
</LinearLayout>
</HorizontalScrollView>
Then I have the following code
private List<Button> yearButtons;
private static final int[] YEAR_BUTTON_IDS = {
R.id.currentYear,
};
Then I must find out what year it is and overwrite my current button
int firstYear = Integer.parseInt(year);
yearButtons.get(0).setText(String.valueOf(CurrentYear));
then in my init class I substantiate the buttons, I understand I do not need a loop for only 1 button but leaving it like this for consistency with how the months buttons work
for(int id : YEAR_BUTTON_IDS) {
Button button = (Button)findViewById(id);
button.setOnClickListener(this);
yearButtons.add(button);
}
Then I have some logic to find out the first year they started called yearsOfTransactions
Then I have the following loop where I try create the buttons
for (int i =0; i< yearsOfTransactions; i++){
int yearToAdd = CurrentYear-i-1;
Button myButton = new Button(this);
myButton.setText(String.valueOf(yearToAdd));
yearButtons.add(myButton);
}
However this is not working..
Thanks for any help
I am making slight modification in your code :
<HorizontalScrollView
android:id="#+id/yearScrollView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/white"
android:layout_gravity="center">
<LinearLayout
android:id="#+id/button_parent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/currentYear"
android:tag="01"
android:text="2015"
android:paddingLeft="8.0dip"
android:paddingRight="8.0dip"
android:height="24dp"
android:textSize="18sp"
android:textColor="#333333"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/white"
>
</Button>
</LinearLayout>
</HorizontalScrollView>
Now make an array of years to add (in onCreate())
int[] yearToAdd = {2000, 2001, 2002, 2003};
LinearLayout parentLayout = (LinearLayout)findViewById(R.id.button_parent);
for (int i =0; i< yearToAdd.lenght; i++){
int yearToAdd = yearToAdd[i];
Button myButton = new Button(this);
myButton.setText(String.valueOf(yearToAdd));
yearButtons.add(myButton);
yearButtons.setOnClickListener(this);
parentLayout.addView(myButton);
}
Let me know in case of more clearation you need, hope it will help :)
you have to add button to a linear layout.
This is a function i use to add dynamic buttons in a linear layout.
public Button createButton(String label) {
Button button = new Button(mContext);
button.setText(label);
mDynamicLayout.addView(button, mLayoutParam);
return button;
}
You should add every button you create to the LinearLayout. First set and id in xml to LinearLayout. Find the view in your class and, finally, add the buttons.
LinearLayout container = findViewById(R.id.container);
//...
for (int i =0; i< yearsOfTransactions; i++){
int yearToAdd = CurrentYear-i-1;
Button myButton = new Button(this);
myButton.setText(String.valueOf(yearToAdd));
yearButtons.add(myButton);
// you missed that
container.addView(myButton);
}
please try this inside your for loop
LinearLayout layout = (LinearLayout) findViewById(R.id.linear_layout_tags);
//set the properties for button
Button btnTag = new Button(this);
btnTag.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
btnTag.setText("Button");
btnTag.setId(some_random_id);
//add button to the layout
layout.addView(btnTag);

Set button centerHorizontal

I know there are some questions about this topic but neither did work for me. I have created a simple button in a RelativeLayout and when I click on it I'd like the button to jump in the middle of the screen. So I have to set the button to CenterHorizontal and CenterVertical programatically.
Here is my code to set the button centerHorizontal:
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button)findViewById(R.id.button);
final RelativeLayout.LayoutParams layoutParams =
(RelativeLayout.LayoutParams)btn.getLayoutParams();
layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL,0);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btn.setLayoutParams(layoutParams);
}
});
}
And here is my xml:
<RelativeLayout 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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"/>
</RelativeLayout>
When I press the button nothing happens. If anyone has an idea how to fix it please response.
So i found a few problems in your code:
1. You have to add the rule after a button click because you create a reference betwen the variable "layoutParams" and the object.
2.You need to get rid of the existing rules.
Sample code:
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, 0);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_START, 0);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
btn.setLayoutParams(layoutParams);
}
});
You have to remove your align left rules which you have defined in the xml.
Button btn = (Button)findViewById(R.id.button);
RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) btn.getLayoutParams();
lp.addRule(RelativeLayout.CENTER_HORIZONTAL, 1);
lp.removeRule(RelativeLayout.ALIGN_PARENT_START);
lp.removeRule(RelativeLayout.ALIGN_PARENT_LEFT);
btn.setLayoutParams(lp);
keep in mind that RelativeLayout.LayoutParams.removeRule is only supported for API >= 17

add LinearLayout when I press "add button"

I want to add more LinearLayout in a empty one when I press "add button".
When I press the first time "it works", the empty LinearLayout show that I want but if I press the button again don't work ( LogCat show me that occurs a NullPointerException). I see that its not create a new one LinearLayout below the previous one and no idea how solve it.
Let me show you part of my code:
First, I created
static int ID=0;
...
LinearLayout mLayout []= new LinearLayout[10];
...
OnCreate:
...
mLayout[ID] = (LinearLayout) findViewById(R.id.linearLayout_expandir);
...
Then:
private OnClickListener onClick() {
// TODO Auto-generated method stub
return new OnClickListener() {
#Override
public void onClick(View v) {
mLayout[ID].addView(createNewTextView("Contain: ", ID));
mLayout[ID].addView(createNewEditText(ID));
mLayout[ID].addView(createNewTextView("Nº Liter: ",ID));
mLayout[ID].addView(createNewEditText(ID));
ID++;
}
};
}
XML: (This LinearLayout is empty: no EditText, Buttons etc and is inside another LinearLayout)
(More code from other LinearLayouts)
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.66"
android:orientation="horizontal"
android:id="#+id/linearLayout_expandir">
</LinearLayout>
(More code from other LinearLayouts)
Thank you for your time!
One question: you only have 1 LinearLayout, why do you create an array of LinearLayout while you're not adding another LinearLayout to the LinearLayout?
The error probably occurred when the ID become 1, mLayout[1] has not been initialized and you're trying to add another view to it.
LinearLayout expandir = (LinearLayout) findViewById(R.id.linearLayout_expandir);
in the onClick() method:
public void onClick(View v) {
LinearLayout linearLayout = new LinearLayout(context);
linearLayout.addView(createNewTextView("Contain: ", ID));
linearLayout.addView(createNewEditText(ID));
linearLayout.addView(createNewTextView("Nº Liter: ",ID));
linearLayout.addView(createNewEditText(ID));
expandir.addView(linearLayout);
ID++;
}
I've created a solution for you. This activity has a button that will generate layouts for you. I use an arraylist instead of an array but the idea is the same.
This is a picture of many nested layouts that have been created using this demo.
Once you get this code in your project, you will just have to add the TextView/Edit Text code that you mentioned. Let me know if you have any questions. :)
public class LinearLayoutActivity extends Activity {
/*This linear layout is the first container*/
LinearLayout outerMostLayout;
/*This array holds the linear layouts that you will create dynamically*/
List<LinearLayout> subLayouts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_linear_layout);
// Initialize your views
outerMostLayout = (LinearLayout) findViewById(R.id.container_layout);
subLayouts = new ArrayList<LinearLayout>();
Button button = (Button) findViewById(R.id.button);
// Set the button onclick
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Get a reference to the container layout
LinearLayout container = outerMostLayout;
if (!subLayouts.isEmpty()) {
// Check to see if we have created any yet new containers yet
//-- If we have, then use the newest container
container = subLayouts.get(subLayouts.size() - 1);
}
// Initialize the new layout with padding to show the change
LinearLayout linearLayout = new LinearLayout(LinearLayoutActivity.this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams linearLayoutParams = new LinearLayout.LayoutParams(
android.widget.LinearLayout.LayoutParams.MATCH_PARENT,
android.widget.LinearLayout.LayoutParams.MATCH_PARENT);
linearLayout.setLayoutParams(linearLayoutParams);
linearLayout.setPadding(16, 16, 16, 16);
// Add textview with linear layout name
TextView textView1 = new TextView(LinearLayoutActivity.this);
textView1.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
textView1.setText("Linear Layout: " + (subLayouts.size() + 1));
textView1.setBackgroundColor(0xff66ff66); // hex color 0xAARRGGBB
linearLayout.addView(textView1);
// Add the layout to the array
subLayouts.add(linearLayout);
// Set the color of the new layout so that we can see the change
int size = subLayouts.size();
if (size % 2 == 0) {
// Every even layout will be blue
linearLayout.setBackgroundColor(getResources().getColor(R.color.blue));
} else {
// every odd layout will be red
linearLayout.setBackgroundColor(getResources().getColor(R.color.red));
}
// Finally, add the linear layout to the container layout
container.addView(linearLayout);
}
});
}
}
Here is the Layout xml
<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:background="#color/red"
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">
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Generate"/>
<LinearLayout
android:id="#+id/container_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/blue"
android:orientation="horizontal"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin">
</LinearLayout>
</LinearLayout>

Create certain number of EditTexts based on User Input in Android

How would I display a certain number of EditTexts on an Android layout based on user input? For example, I am creating a simple GPA Calculator app, and I need the multiple EditTexts based on however many classes the user is taking. I want to make the range from 1 to 6 classes. Would the easiest way be to create 6 EditText fields and only display however many the user needs when he or she specifies, or is there a better way to do this?
Thank you!
You can create the EditText programatically.
btnClick.setOnClickListener(new OnClickListener(){
//loop based on classes needed
EditText myEditText = new EditText(context); // Pass it an Activity or Context
myEditText.setLayoutParams(new LayoutParams(..., ...)); // Pass two args; must be LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, or an integer pixel value.
myLayout.addView(myEditText);
});
Check this out.
// Try this way,hope this will help you...
**activity_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"
android:padding="5dp" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/edtNoCreate"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="Enter no EditText wan create"
android:inputType="number"/>
<Button
android:id="#+id/btnCreate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Create"/>
</LinearLayout>
<ScrollView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:layout_marginTop="5dp">
<LinearLayout
android:id="#+id/lnrDynamicEditTextHolder"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
</ScrollView>
</LinearLayout>
**MainActivity.java**
public class MainActivity extends Activity{
private LinearLayout lnrDynamicEditTextHolder;
private EditText edtNoCreate;
private Button btnCreate;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lnrDynamicEditTextHolder = (LinearLayout) findViewById(R.id.lnrDynamicEditTextHolder);
edtNoCreate = (EditText) findViewById(R.id.edtNoCreate);
btnCreate = (Button) findViewById(R.id.btnCreate);
btnCreate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(edtNoCreate.getText().toString().length()>0) {
try {
lnrDynamicEditTextHolder.removeAllViews();
} catch (Throwable e) {
e.printStackTrace();
}
int length = Integer.parseInt(edtNoCreate.getText().toString());
for (int i=0;i<length;i++){
EditText editText = new EditText(MainActivity.this);
editText.setId(i+1);
editText.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
editText.setHint("EditText "+(i+1));
lnrDynamicEditTextHolder.addView(editText);
}
}
}
});
}
}
for(int i=0;i<3;++i)
{ LinearLayout layout=(LinearLayout)findViewById(R.id.linearLayout);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
android.widget.LinearLayout.LayoutParams.MATCH_PARENT,
android.widget.LinearLayout.LayoutParams.WRAP_CONTENT);
EditText edttext= new EditText(this);
edttext.setId(i);
edttext.setLayoutParams(params);
layout.addView(edttext);}
}

Android: dynamically set the position of button into center of screen in RelativeLayout

There has been many questions on dynamically setting the position of a button, but I just want to change the position of a button into center of the screen. My layout is RelativeLayout.
Updated:
At the beginning, myButton has been set position in XML as:
<Button
android:id="#+id/myButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:text="Menu" />
Any suggestion would be greatly appreciated
See an example below (click the button and it will be moved to the center).
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/root"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="#+id/my_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:text="Menu" />
</RelativeLayout>
MainActivity.java:
public class MainActivity extends Activity {
private View mView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mView = findViewById(R.id.my_view);
mView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ViewGroup.LayoutParams vg_lp = mView.getLayoutParams();
// Make sure we are in RelativeLayout
if (vg_lp instanceof RelativeLayout.LayoutParams) {
RelativeLayout.LayoutParams rl_lp = new RelativeLayout.LayoutParams(vg_lp);
rl_lp.addRule(RelativeLayout.CENTER_IN_PARENT);
mView.setLayoutParams(rl_lp);
}
}
});
}
}
Try:
......
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) button.getLayoutParams();
layoutParams.leftMargin = parentLayout.getWidth()/2;
layoutParams.topMargin = parentLayout.getHeight()/2;
button.setLayoutParams(layoutParams);
......
Try this one:
RelativeLayout RL = (RelativeLayout)findViewById(R.id.relative_layout);
RL.gravity(Gravity.CENTER);
with this all subviews of RL will be in center;
Button anyButton = new Button(this);
RL.addSubview(anyButton);//this genereted button will be in center as well
Try this,
RelativeLayout my_layout = new RelativeLayout(this);
my_layout.setId(some_value);
Button my_btn = new Button(this);
RelativeLayout.LayoutParams my_params = new RelativeLayout.LayoutParams(btn_height,btn_width);
my_params.addRule(RelativeLayout.CENTER_IN_PARENT,my_layout.getId());
my_layout.addView(my_btn,my_params);
Add this 2 lines to the component you want to center in the xml file :
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"

Categories

Resources