dynamicaly adding controls in android onbutton click - android

This is what i am doing in coding i want to create controls on button click. The number of times the user will click i want to add controls for the same number of time..
I have to add these controls in relative layout. which i had already created in xml layout with one set of controls already in it.. and want to make it working for more controls if user want to edit.
View DynamicView= new View(this);
DynamicView.setId(123);
DynamicView.setLayoutParams(new LayoutParams(1, LayoutParams.MATCH_PARENT))
The following is XML layout code.
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#android:color/black" />
problems:-
1) dont want to give ids this way :(
DynamicView.setId(123);
want to assign such ids as we can assign in xml layout
android:id="#+id/spnrIngredients1"
2) how to give values for relative layouts in coding such as
android:layout_toRightOf="#id/tvIngredientsName"
android:layout_toLeftOf="#id/tvIngredientsName"
android:layout_below="#id/tvIngredientsName"
android:layout_above="#id/tvIngredientsName"
3) how to give values for background colors.
it is not accepting hexadecimal codes or something else.. what type of int values it is asking for..?

2) Use the LayoutParams to set the rules for placing the views in the RelativeLayout:
Button b = new Button(this);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.BELOW, viewID);
b.setLayoutParams(lp);
b.setText("Added at Bottom");
mParent.addView(b, lp);
The above code will place the Button bellow the view with the id viewID.
3) setBackgroundColor()(I think this is the method you are using) requires an int representing the Color, you can set it in that method this ways:
Color.RED
Color.parse(Color.parseColor("#0077cc"))
android.R.color.black
1) You could set your ids in a values/ids.xml file and later set them to your views and then refer the views by those ids:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item type="id" name="myfirstid" />
</resources>
Now you can use the id R.id.myfirstid in your code(I don't know if this is what you want).
NOTE:
I don't know if this is recommended.

Related

Setting the text of a programatically created button

Basic question regarding setting the text of a programatically created button. As seen in my code below I've done the basics in terms of creating the button but my button appears as seen in my attached image. Basically the text in the button doesn't appear as expected. Any ideas why?
Note: I've declared button as a public instance variable right above my onCreate() and has been added correctly to my relative layout using addView();
// Create User button
btnUserAdmin = new Button(this);
// Customise the UserAdmin button
btnUserAdmin.setBackgroundColor(Color.BLUE);
btnUserAdmin.setTextSize(13.7f);
btnUserAdmin.setTextColor(Color.parseColor("#FFCC00"));
btnUserAdmin.setText("USER ADMINISTRATION");
btnUserAdmin.setGravity(Gravity.LEFT);
Thanks.
You should specify the dimensions of the button, otherwise the size could be unexpected. For instance
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.MATCH_PARENT );
btnUserAdmin.setLayoutParams(lp);
also, you can directly set them when you add the buttom
yourRelativeLatout.addView(btnUserAdmin, lp);
Also remember that numeric values for the dimensions (of the bottom or the layout) usually are evil. As you can, use only WRAP_CONTENT and MATCH_PARENT

Adding Textviews Dynamically goes out of focus to a Linear Layout

I am trying to achieve a dynamic list of textviews like in the image below :-
Here is my code :-
LayerDrawable dashboardResShape_community= (LayerDrawable) getResources().getDrawable(R.drawable.upcomingtask_tags_shape);
// The background effect is by the layer list drawable from the above code
LinearLayout tags_view2=(LinearLayout)findViewById(R.id.tags_view);
LayoutParams lp = new LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp.setMargins(10, 2, 2, 2);
TextView[] tx = new TextView[15];
for(int i=0; i<15; i++) {
tx[i] = new TextView(getActivity());
tx[i].setPadding(8, 4, 8, 4);
tx[i].setBackground(dashboardResShape_community);
tx[i].setLayoutParams(lp);
tx[i].setText("Tag"+i);
tags_view2.addView(tx[i]);
}
and in my xml there is only a linear layout :-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tags_view"
android:orientation="horizontal" >
</LinearLayout>
This is what i achieve :-
When i am adding 15 textviews, only 8 are shown like below, the rest should come in the next line but they are not.
If i add more textviews, it goes out of screen but i want to add the textview in the second line when the first line is full. What i am doing wrong here?
Its LinearLayout's limitation.
If you want the explained behavior than
You have to make your own Layout/View refer this link or
Impliment LinearLayout Horizontal orientation with wrapping children like this
you cannot get more text views on next line after linear layout is filled( screen width ), you already the made linear layout orientation as horizontal. Better solution add one more linear layout or use relative (do some child count coding and set parameters). The best solution i prefer for u is table layout. Easier to code code and handle
What you can do is add as many textviews as will fit on the screen to your linearlayout, but then when a textview would go off the screen, you could add another linearlayout below the one that you already had, and then add on to that. You could keep doing that and you would end up with no textviews goind off the screen. You could also try using a gridview.
Here is what this layout looks like:
http://developer.android.com/guide/topics/ui/layout/gridview.html
And here is the documentation:
http://developer.android.com/reference/android/widget/GridView.html

dynamically created Buttons overlapping

I have created a layout with a database call where a button will be created for each item inside the database. The buttons are created like I need and I also found out, how to set up the layout_width and layout_height but all buttons are placed in the same position and overlap each other so that only the last created button can be accessed. My code for creating the buttons looks like this:
Button bt = new Button(this);
bt.setText("Button Title");
bt.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
linerLayout.addView(bt);
The activity looks like that, after generating the buttons:
I looked at each method that can be used for the button but didn't find anything to define the position. I just thought about following method:
bt.layout(l, t, r, b);
but don't know exactly how to use it and thought there might be a simpler method to solve this problem. Anybody who knows a workaround?!
CHANGED CODE
I just tryied to set the layout parameters like explained from "Chen doron". I have a relative layout inside my xml file:
<RelativeLayout
android:id="#+id/llActOver"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="2" >
</RelativeLayout>
and formatted the generated buttons like this:
Button bt = new Button(context);
bt.setText(c.getString(iDef));
fontClass.setFont(bt);
//RelativeLayout placeholder = new RelativeLayout(context);
RelativeLayout.LayoutParams layoutParam =
new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT);
if(rowCount < 1){
layoutParam.addRule(RelativeLayout.ALIGN_PARENT_TOP);
rowCount++;
}else{
layoutParam.addRule(RelativeLayout.ALIGN_PARENT_TOP, lastButtonId);
}
lastButtonId = bt.getId();
//placeholder.addView(bt, layoutParam);
linearLayout.addView(bt, layoutParam);
I save the buttons id at the end of the loop so that the last buttons id can be accessed in the next round.
I also tryied to create a new relativ layout for each new button like the commented part of the code shows but even without the new layout nothing happens and i still just have all buttons overlapped.
I finally solved the problem, but just by trying each possible combination of layout types.
I found out, i have to define a LinearLayout inside the XML file and the attribute android:orientation="vertical" is affordable. all the other parameters that have been set before were unimportant.
So now i have a LinearLayout inside a ScrollView in my xml file:
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="2" >
<LinearLayout
android:id="#+id/llActOver"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
</LinearLayout>
</ScrollView>
and inside the java database i have following code to create a button for each row in the db, setting its Text and Font and add it to the loaded layout:
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
Button bt = new Button(context);
bt.setText(c.getString(iDef));
fontClass.setFont(bt);
linearLayout.addView(bt);
}
and here a screenshot of the result:
maybe somebody else who has the same problem won't need to worry as long as me with this description.
You could use a Relative Layout, and have the first Button align to the parent's top.
Then each button aligned to the previous button's bottom.
Use:
params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
And then:
params.addRule(RelativeLayout.BELOW,ID-Of-Previous-Button);
Also check out:
http://developer.android.com/reference/android/widget/RelativeLayout.LayoutParams.html

RelativeLayout add rule "RelativeLayout.LEFT_OF" not working

I have a relativeLayout like below:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:id="#+id/parent" >
<ListView
android:layout_width="360dp"
android:layout_height="600dp"
android:id="#+id/list"
android:inputType="text"
android:maxLines="1"
android:layout_margin="50dp"
android:layout_alignParentRight="true"
/>
</RelativeLayout>
In the java code, I want to add a view to the left of the listview, but it didn't worked:
m_relativeLayout = (RelativeLayout)findViewById(R.id.parent);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
layoutParams.addRule(RelativeLayout.LEFT_OF, m_listView.getId());
Button button2 = new Button(this);
button2.setText("I am button 2");
m_relativeLayout.addView(button2, layoutParams);
only if I set the listview to alignParentRight, it will work. Is this an android bug or I'm missing something?
I always try addView(View child, int index, LayoutParams params), but it might only work in the linearlayout. So is there an normal solution to make the RelativeLayout.LEFT_OF work?
EDIT
I have tried RelativeLayout.BELOW and RelativeLayout.RIGHT_OF, and they worked perfectly, so it means I don't have enough place to get the button? I tried to give more space, but it still not work.
I use Toshiba AT100 (1280*800) and landscape, so the space is enough. Test below and right just same as the left. I think If i put an control A in the relativelayout, then I add control B and decalare it's on the left of the control A, the result should be the control B will push the control A to its right, right?
I think If i put an control A in the relativelayout, then i add control B and declare it's on the left of the control A, the result should be the control B will push the control A to its right, right?
Your assumption is incorrect, the control A will not be pushed to the right unless you specified this with a RelativeLayout.LayoutParams rule. RelativeLayout places its children one one top of each other starting at the top-left corner of the screen if you don't specify placement rules for them. When you add the View A to the RelativeLayout without any rules(like layout_alignParentRight) it will be placed starting from the top-left corner of the screen. Then, when you add the View B, the rule to_leftOf will apply to this View position but this rule doesn't mean anything for the View A who will maintain its position on the screen. This will make View B to be place to the left of View A but outside of the screen as View A bounds start from the left border of the screen.
The Button will be placed to the left of the ListView when you use layout_alignParentRight="true" because there is now space to actually see the Button(it's not outside anymore). addView(View child, int index, LayoutParams params) works in a LinearLayout because the LinearLayout arranges its children in a row or column(depending on orientation) so when you add a View at a specific position, it will push the other Views after it to the right or below(depending on orientation)(there is no relative positioning of the views in a LinearLayout, the only rule is that the children come one after the other).
Starting with the ListView without any rules set on it, here is an example on how to make the Button to appear on the left of the ListView:
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
Button button2 = new Button(this);
button2.setText("I am button 2");
button2.setId(1000);
m_relativeLayout.addView(button2, layoutParams);
RelativeLayout.LayoutParams rlp = (RelativeLayout.LayoutParams) m_listView
.getLayoutParams();
rlp.addRule(RelativeLayout.RIGHT_OF, button2.getId());
The Button will be added as normal to the screen and it will appear starting from the top-left corner of the screen. Without the two lines from the code above the Button and ListView will overlap as this is the normal behavior of RelativeLayout for children without any rules on them. We then explicitly modify the position of the ListView to move it to the right(with the last two line from the code above).
If your variable names are indicative, it's because you are adding the widget to a LinearLayout, so tags for a RelativeLayout get ignored.
This line is the one I'm talking about:
m_linearLayout.addView(button2, layoutParams);
EDIT
You say alignParentRight works... the only difference there is that ot doesn't take an anchor parameter. Perhaps m_listView.getId() isn't returning the proper id. You could step through with the debugger and see if it's returning a proper value.
Maybe you could try calling the id specifically...
layoutParams.addRule(RelativeLayout.LEFT_OF, R.id.list);
To perform it, use predefined view ID or declare one. In values folder create ids.xml then add a Item like this:
<item name="imageViewID" type="id"/>
use this id in your code where you are creating new Instance of view like this:
RelativeLayout layout=new RelativeLayout(context);
ImageView imageView = new ImageView(context);
imageView.setId(R.id.imageViewID);
RelativeLayout.LayoutParams layoutParams = new LayoutParams(50, 50);
layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
layout.addView(imageView, layoutParams);
TextView textView = new TextView(context);
RelativeLayout.LayoutParams textViewParams= new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
textViewParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
textViewParams.addRule(RelativeLayout.BELOW, imageView.getId());
layout.addView(nameView, nameLayoutParams);
or we can directly use this function View.generateViewId() to perform the same. Like this:
imageView.setId(View.generateViewId());
I think you might have forgotten to add m_listView to the RelativeLayout or m_listView's visibility would be GONE.
Can you please check for that?
setId before align is called, especially for the new object view.
If you are using a custom id and not a regular generated Android id (eg. R.id.my_id), make sure that the id is not equal to 0 (or negative), otherwise the rule will be ignored.

How can I abolish addRule-Rules?

I created a field of buttons in my XML file:
<RelativeLayout...>
<Button
android:id="#+id/button_1"
...
/>
<Button
android:id="#+id/button_2"
android:layout_toRightOf="#+id/button_1"
...
/>
...
</RelativeLayout>enter code here
Now I want to abolish the XML rule "toRightOf" programmaticaly.
I know how to set rules:
RelativeLayout.LayoutParams params = null;
params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.RIGHT_OF, topIcon.getId());
button_2.setLayoutParams(params);
But I want to DELETE rules I had set in XML file.
How can this be done?
The background of my question: I used an XML file to easily
create field of buttons.
But later I want to drag and drop buttons.
For that I have to delete rules like "toRightOf".
Otherwise instead of one button a lot of buttons
move if I only want to move one button.
Looking at this question, it cannot be removed but instead you set the value to 0:
layoutParams.addRule(RelativeLayout.RIGHT_OF, 0);

Categories

Resources