Dynamically add buttons to an already existing array of buttons - android

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);

Related

Adding views programatically to a relative layout within a scrollview

Please bear with me as I am new to the use of Views and Layouts.
I am trying to create an application in which the user can enter a text field, press a button and have a new text field appear and they can continue adding text fields in this way.
My solution was to have the top level be a scrollview and then have a relative view as a child within that(this way I can then programatically insert more editviews in my code with the OnClick() listener.
I have seen and read a couple of other posts pertaining to relative views but it seems there is still something that I am missing. I have tried
Here is the xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_create_accounts"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.nic.mybudget.CreateAccountsActivity">
<RelativeLayout
android:id="#+id/activity_create_accounts_relativeLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fillViewport="true"
>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/activity_name"
android:inputType="textAutoComplete"
android:layout_alignParentTop="true"
android:id="#+id/activity_createAccounts_relativeLayout_activityName"/>
<Button
android:text="+"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_below="#+id/activity_createAccounts_relativeLayout_activityName"
android:id="#+id/activity_create_accounts_relativeLayout_activityName_addButton" />
<Button
android:text="Save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_below="#+id/activity_create_accounts_relativeLayout_activityName_addButton"
android:layout_centerHorizontal="true"
android:id="#+id/activity_create_accounts_relativeLayout_activityName_saveButton" />
</RelativeLayout>
And here is the Code where I try to add new editviews.
public class CreateAccountsActivity extends Activity {
static private final String TAG = "MAIN-Activity";
int numAccounts = 0;
int lastAccountID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_accounts);
final RelativeLayout Relative = (RelativeLayout) findViewById(R.id.activity_create_accounts_relativeLayout);
final TextView oldAccount = (TextView) findViewById(R.id.activity_createAccounts_relativeLayout_activityName);
final TextView newAccount = new TextView(this);
final Button addNewAccountButton = (Button) findViewById(R.id.activity_create_accounts_relativeLayout_activityName_addButton);
addNewAccountButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i(TAG, "addNewAccountOnClick");
numAccounts = numAccounts+1;
int newAccountID = oldAccount.getId() + numAccounts;
RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
rlp.addRule(RelativeLayout.ALIGN_PARENT_TOP);
newAccount.setLayoutParams(rlp);
newAccount.setHint("Hint" );
newAccount.setId(newAccountID);
Relative.addView(newAccount);
RelativeLayout.LayoutParams blp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
blp.addRule(RelativeLayout.BELOW, newAccountID-1);
addNewAccountButton.setLayoutParams(blp);
}
});
}
}
As you can see what I am trying (and failing) to do is add the new edit view at the top of the page and simply push everything else down the page. What am I getting wrong here with the relative layout?
Any help is appreciated.
First thing View with id activity_createAccounts_relativeLayout_activityName is EditText and you are casting it with TextView so that is wrong cast it to EditText.
And to your actual problem:
You are using same EditText instance with variable newAccount and adding it again in relative layout if you want to add one more EditText in relative layout you have to initialise EditText inside onclicklistener.
Just add one line newAccount= new EditText(context)in your onclicklistener code before line numAccounts = numAccounts+1;
Happy Coding !

Remove all images created by Imageview

I am creating n number of images with wordImage and assign a differnt Id.This happens on a button click add. There is another button remove when I click that all the images that I have created should be removed from the view(Head is the view). Plz help how to do that.
onclick of add button
for (int getwordcount = 0; getwordcount <5; getwordcount++) {
int i=0;
WordImage = new ImageView(this);
WordImage.setId(getwordcount);
WordImage.setBackgroundResource(alphabetsimages[getwordcount]);
RelativeLayout.LayoutParams para=new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.FILL_PARENT,
RelativeLayout.LayoutParams.FILL_PARENT);
para.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
para.leftMargin=maragin+=54;
para.bottomMargin=25;
para.width=BtnNext.getWidth()/3;
para.height=BtnNext.getHeight();
WordImage.setLayoutParams(para);
WordImage.setTag(getSplitString);
Head.addView(WordImage);
}
onclick of remove button
only the last -------------> Head.removeView(WordImage);
create image is removed from view.
How do I remove all images created using wordimage.Any help would be greatly appreciated.
WordImage saves link just for the last ImageView. Previous link lost in this line:
WordImage = new ImageView(this);
This is why Head.removeView(WordImage) removes only the last image.
If you want delete all added image elements, the easiest way do this is to add RelativeLayout container like this:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<RelativeLayout android:id="#+id/Head" android:layout_width="wrap_content" android:layout_height="wrap_content"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="add"
android:onClick="onClickAdd"
android:id="#+id/button" android:layout_alignParentStart="true"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="remove"
android:onClick="onClickRemove"
android:layout_alignBaseline="#id/button"
android:layout_alignParentRight="true"/>
</RelativeLayout>
Then you can delete all images only by one command:
Head.removeAllViews();
In other case, if you need to remove separate images, you have to delete your items in cycle similar to your "add" block:
for (int getwordcount = 0; getwordcount <alphabetsimages.length; getwordcount++) {
Head.removeView(findViewById(getwordcount));
}
Activity class will be like this:
public class MyActivity extends Activity {
RelativeLayout Head;
int alphabetsimages[] = {android.R.drawable.arrow_down_float, android.R.drawable.btn_dropdown, android.R.drawable.btn_minus, android.R.drawable.ic_dialog_map};
ImageView WordImage;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void onClickAdd(View v){
int margin = 0;
for (int getwordcount = 0; getwordcount <alphabetsimages.length; getwordcount++) {
int i=0;
WordImage = new ImageView(this);
WordImage.setId(getwordcount);
WordImage.setBackgroundResource(alphabetsimages[getwordcount]);
RelativeLayout.LayoutParams para=new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.FILL_PARENT,
RelativeLayout.LayoutParams.FILL_PARENT);
para.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
para.leftMargin=margin+=54;
para.bottomMargin=25;
para.width = 40;
para.height = 40;
WordImage.setLayoutParams(para);
Head= (RelativeLayout)findViewById(R.id.Head);
Head.addView(WordImage);
}
}
public void onClickRemove(View v){
//Head.removeAllViews();
for (int getwordcount = 0; getwordcount <alphabetsimages.length; getwordcount++) {
Head.removeView(findViewById(getwordcount));
}
}
}
I hope that's what you need!

How to align these 2 buttons next to each other programmatically in Android?

I have written this piece of code. But it is not giving the proper result. Please let me know where is the mistake. And I don't want to use Linear Layout.
Here is the xml file
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<RelativeLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/custom_relativeLayout1"
android:orientation="horizontal"
android:background="#ffffff">
</RelativeLayout>
</LinearLayout>
String[] but = {"Hello", "Bye"};
int buttonCount = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
customLayout = (RelativeLayout) findViewById(R.id.custom_relativeLayout1);
//customLayout is object of relativelayout.
buttonCount = but.length;
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
Button [] butArray = new Button[buttonCount];
for (int i = 0; i < 2; i++)
{
butArray[i] = new Button(this);
butArray[i].setLayoutParams(params);
RelativeLayout.LayoutParams Btnparams = (RelativeLayout.LayoutParams) butArray[i].getLayoutParams();
butArray[i].setText(but[i]);
butArray[i].setId(i+1); // Setting the ids
butArray[i].setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_launcher, 0, 0);
butArray[i].setBackgroundColor(Color.TRANSPARENT);
if (butArray[i].getId() != 1)
{
Btnparams.addRule(RelativeLayout.RIGHT_OF, butArray[i-1].getId());
butArray[i].setLayoutParams(Btnparams);
customLayout.addView(butArray[i]);
}
else
{
butArray[i].setLayoutParams(Btnparams);
customLayout.addView(butArray[i]);
}
}
RelativeLayout.RIGHT_OFhoryzontally or vertically align?
so for vertically
Btnparams.addRule(RelativeLayout.BELOW, butArray[i-1].getId());
customLayout.addView(butArray[i], Btnparams);
or for horizontally
Btnparams.addRule(RelativeLayout.RIGHT_OF, butArray[i-1].getId());
customLayout.addView(butArray[i], Btnparams);
instead of
Btnparams.addRule(RelativeLayout.RIGHT_OF, butArray[i-1].getId());
butArray[i].setLayoutParams(Btnparams);
customLayout.addView(butArray[i]);
LinearLayout is very nice to use if you want do dynamically add Views and scale them the same. For example if you want to add buttons and have max 3 buttons per row, you can also use another LinearLayout to make a new row.
I 'abuse' the LinearLayout row and a Button for layoutparams templating.
Layout file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/ll_root"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout android:id="#+id/ll_row1"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="#+id/btn1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button 1"/>
<Button
android:id="#+id/btn2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button 2"/>
</LinearLayout>
</LinearLayout>
Example code:
// Get LL and template params
LinearLayout root = (LinearLayout) findViewById(R.id.ll_root);
LinearLayout row1 = (LinearLayout) findViewById(R.id.ll_row1);
ViewGroup.LayoutParams llRowParams = row1.getLayoutParams();
ViewGroup.LayoutParams btnParams = findViewById(R.id.btn1).getLayoutParams();
// Make new button
Button newBtn = new Button(context);
newBtn.setLayoutParams(btnParams);
newBtn.setText("Button 3");
// Add button to row1
row1.addView(newBtn);
// Add new row
LinearLayout row2 = new LinearLayout(context);
row2.setLayoutParams(llRowParams);
root.addView(row2);
// TODO: add buttons to new row
// TODO: some logic to decide between adding to row or creating new row and adding button
Note: code is not tested, but you should get the idea.
buttonCount = but.length;
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
Button [] butArray = new Button[buttonCount];
for (int i = 0; i < 2; i++)
{
butArray[i] = new Button(this);
butArray[i].setLayoutParams(params);
RelativeLayout.LayoutParams Btnparams = (RelativeLayout.LayoutParams) butArray[i].getLayoutParams();
butArray[i].setText(but[i]);
butArray[i].setId(i+1); // Setting the ids
butArray[i].setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_launcher, 0, 0);
butArray[i].setBackgroundColor(Color.TRANSPARENT);
if (i != 0) {
Btnparams.addRule(RelativeLayout.RIGHT_OF, i-1);
}
customLayout.addView(butArray[i], Btnparams);
}

Android: Adding buttons at runtime

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);

Add radio button dynamically in an Android app

I need to add radio button dynamically. A radio button may be 3, 4, 5 or 6 and it would be added horizontally and one row contains maximum 3 radio button.
If there are more than 3 then it would come below of above row of radio button as in grid view. My code for radio button are below but it display all radio button in a single row, means it's hiding the radiobutton.
main.xml:
<?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" >
<TextView
android:id="#+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Choose Your Favorite Actress" >
</TextView>
<RadioGroup
android:id="#+id/RadioGroup01"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</RadioGroup>
<Button
android:id="#+id/Button01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit" >
</Button>
</LinearLayout>
And Java class is:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DisplayRadioButton();
}
public void DisplayRadioButton() {
for(int i=0;i<10;i++) {
RadioGroup radiogroup = (RadioGroup)findViewById(R.id.RadioGroup01);
RadioButton rdbtn = new RadioButton(this);
rdbtn.setId(i);
rdbtn.setText(text[i]);
radiogroup.addView(rdbtn);
}
}
please try in the following way:
1)in your xml remove the RadioGroup. create it by dynamically
RadioGroup radiogroup[];
RadioButton rdbtn[];
LinearLayout linear[];
radiogroup = new RadioGroup[9/3];
rdbtn = new RadioButton[9];
linear = new LinearLayout[9/3];
......
int count = 0; // integer flag
for(int i=0;i<9;i++){
if the value of i is equal to 3 multiple then increase count by 1
// sett linear[count]'s orientation is horizontal.
root_layout.addView(linear[count]);
radiogroup[count] = new RadioGroup(this);
linear[count].addView(radiogroup[count]); // add radio group to linear layout
add radio button to radio group.
rdbtn[i] = new RadioButton(this);
rdbtn[i].addView(radiogroup[count]);
}
i hope you get solved. be aware of array index out of bound exception.
your xml may look like:
<LinearLayout
android:id= rootlayout
..... // the child linearlayout
.. . radio group
... radio button
</LinearLayout>

Categories

Resources