Since I'm still just learning Android (and it appears Amazon says it'll be 2 months till I get the Hello, Android book) I'm still playing around with doing simple things. I have no problem getting an icon to display with the click of a button on my RelativeLayout using ImageView. The code for creating it is as follows:
private int mIconIdCounter = 1;
private ImageView addIcon(){
ImageView item = new ImageView(this);
item.setImageResource( R.drawable.tiles );
item.setAdjustViewBounds(true);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT );
if( mIconIdCounter != 1 ){
params.addRule(RelativeLayout.RIGHT_OF, 1 );
}
item.setLayoutParams( params );
item.setId( mIconIdCounter );
++m_IconIdCounter;
return item;
}
and the code to add the item is:
Button addButton = (Button)findViewById(R.id.add_new);
addButton.setOnClickListener( new OnClickListener(){
#Override
public void onClick(View view) {
addContentView( addIcon(), new RelativeLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT ) );
}
});
When I click my button what happens is all the newly created views are placed atop one another. I'd like them to be placed to the right of the next element. I did a quick search on SO for articles relating to RelativeLayout and found some that were similar (here, here, here, and here) but while these addressed getting the content into the RelativeView they didn't seem to address the positioning aspect.
What am I doing wrong?
EDIT:
My main xml looks like:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:id="#+id/add_new"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/add_new"
android:layout_alignParentBottom="true" />
</RelativeLayout>
It looks like you might be adding the view to the root of the layout xml instead of the RelativeLayout.
You could try:
RelativeLayout layout = (RelativeLayout)findViewById(R.id.my_layout);
layout.addView(addIcon());
you are creating new relative layout inside function call. So every time new relative layout created and it added in the view when click button . Use common relative layout.
Related
I have been attempting to programmatically add buttons based on a list of values.
PROBLEM: Only one button is produced, rather than a series. This button contains the information of the last value in the array.
I gather an array of values aptly named 'values', I then use a for loop to add the buttons.
Here is the code of my loop to add buttons:
public void updateButtons(List<String> values, View rootView) {
//Find relative layout
RelativeLayout rl = (RelativeLayout) rootView.findViewById(R.id.RelativeLayoutManage);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(50, 10, 50, 10);
for (String mTrip : values) {
//New button
Button Postbtn = new Button(mContext);
//Style
Postbtn.setBackgroundResource(R.drawable.buttonshape);
Postbtn.setTextColor(getResources().getColor(R.color.DarkGreen));
Postbtn.setTextSize(25);
//set text
Postbtn.setText(mTrip.toString());
//set id
Postbtn.setId(i);
int id_ = Postbtn.getId();
//Add to view
rl.addView(Postbtn, params);
Postbtn = ((Button) rootView.findViewById(id_));
//Add listener
Postbtn.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
Log.v("TripNumber", Integer.toString(i));
//TODO: Change Fragment
}
});
i++;
}
}
And my corresponding layout file if needed:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:id="#+id/RelativeLayoutManage"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
</RelativeLayout>
Seems that they might be overlapping each other. You need to use a LinearLayout
<LinearLayout android:id="#+id/RelativeLayoutManage"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
/>
You are adding Button to RelativeLayout. In your current code all your buttons are present but one above other. You should make one below/above other to make all buttons visible. Else use a LinearLayout
I solved the problem by positioning each button as it is added to the layout. Simply using:
params.addRule(RelativeLayout.BELOW, Postbtn.getId() - 1);
Postbtn.setLayoutParams(params);
I'm dynamically adding views to a relative layout and programatically defining them. The views can be moved around the screen so their position is changing.
When I try to set a view (button2) to sit below another view (button1), button2 gets placed in the old location of button1 (the default location of where views get added before moved). I've linked images to hopefully convey this better.
This is the Original Layout
Layout after Button2 is re-positioned
I have a background LinkedList keeping track of all view changes and view attributes for the layout if that makes a difference.
Here are the code functions:
How i'm re-positioning Button1:
Buttons b = (Buttons) viewIndex;
positioningLayout = new RelativeLayout.LayoutParams(b.getLayoutParams());
positioningLayout.addRule(RelativeLayout.CENTER_VERTICAL);
b.setLayoutParams(positioningLayout);
baseLayout.addView(b);
Repositioning views below another view Code fragment:
Buttons b = (Buttons) viewIndex;
positioningLayout = new RelativeLayout.LayoutParams(b.getLayoutParams());
positioningLayout.addRule(RelativeLayout.BELOW, viewIdFromList.intValue());
b.setLayoutParams(positioningLayout);
b.invalidate();
How I'm adding the views to the layout.
uiList.addView(new Buttons(this), "BUTTON");
setDialogView(uiList.getLast());
showDialog(SET_ID);
reloadUI();
setDialogView is just passing the view to the Dialog SET_ID so that I can manually assign an ID to the view (for testing).
reloadUI() just finds the last view added to the background LinkedList and adds it to the relativeLayout using .addView;
If you require more code please let me know. Am I missing a call to update the view layouts after making a change to the relativeLayout child views? It seems like the view is getting re-positioned visually but the actual LayoutParams are not updating so when you set Button2 to Button1 it's getting the old position.
Is there a way to force a relative layout view re-position?
I think you should try simple solution - replace b.invalidate() with b.requestLayout(). For more background check this link. I didn't test it but I hope it will work. So the code should look like:
Buttons b = (Buttons) viewIndex;
positioningLayout = new RelativeLayout.LayoutParams(b.getLayoutParams());
positioningLayout.addRule(RelativeLayout.BELOW, viewIdFromList.intValue());
b.setLayoutParams(positioningLayout);
b.requestLayout();
Or maybe you can simplify this to:
Buttons b = (Buttons) viewIndex;
((RelativeLayout.LayoutParams) b.getLayoutParams()).addRule(RelativeLayout.BELOW, viewIdFromList.intValue());
b.requestLayout();
You seem to be in the right track but is doing a small mistake. Without more code it is quite difficult to provide the actual solution. But I will try to point out the mistake.
See, to relatively position items programmatically in a RelativeLayout you must assign unique ids to each of them.
Like,
Button b = new Button(this);
b.setId(1);
Button c = new Button(this);
c.setId(2);
Each element should have unique ids.
Now if you want to place the Button b vertically in the center,
layout.addRule(RelativeLayout.CENTER_VERTICAL);
b.setLayoutParams(layout);
Now if you want to place Button c below it,
layout.addRule(RelativeLayout.BELOW, b.getId());
layout.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
b.setLayoutparams(layout);
This will certainly place the button c below button b. As you said you can use a any data structure of your choice to keep track of the ids of each elements.
This is only a detail example on how you move the button correctly. So first, create a unique id for the View, i.e. create a new XML resource file in res/values/, and name it ids.xml:
And the content of ids.xml is:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item name="button_1" type="id"/>
<item name="button_2" type="id"/>
</resources>
We have to set an id to your main layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/layout_main"> <!-- the id -->
<!-- content of this layout -->
</RelativeLayout>
Then, let's create the Buttons:
RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.layout_main);
final Button button1 = new Button(this);
button1.setId(R.id.button_1);
button1.setText("BUTTON 1");
button1.setTextColor(Color.BLACK);
final Button button2 = new Button(this);
button2.setId(R.id.button_2);
button2.setText("BUTTON 2");
button2.setTextColor(Color.BLACK);
relativeLayout.addView(button1, new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT));
relativeLayout.addView(button2, new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT));
RelativeLayout.LayoutParams params1 = (RelativeLayout.LayoutParams) button1.getLayoutParams();
params1.addRule(RelativeLayout.CENTER_IN_PARENT); // set to the center of screen
button1.setLayoutParams(params1);
final RelativeLayout.LayoutParams params2 = (RelativeLayout.LayoutParams) button2.getLayoutParams();
params2.addRule(RelativeLayout.ALIGN_PARENT_TOP);
params2.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
button2.setLayoutParams(params2);
button2.setOnClickListener(new View.OnClickListener() {
#SuppressLint("NewApi")
#Override
public void onClick(View v) {
/* We need to remove the existing rules and update it!
* For API 16 and earlier, set the rule to 0, e.g. --> layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, 0);
* For API 17 and higher, call layoutParams.removeRule(RelativeLayout.ALIGN_PARENT_LEFT);
*/
int api = android.os.Build.VERSION.SDK_INT;
if (api >= Build.VERSION_CODES.JELLY_BEAN_MR1) { // API level 17
params2.removeRule(RelativeLayout.ALIGN_PARENT_TOP);
params2.removeRule(RelativeLayout.ALIGN_PARENT_LEFT);
}else if (api < Build.VERSION_CODES.JELLY_BEAN_MR1) {
params2.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
params2.addRule(RelativeLayout.ALIGN_PARENT_LEFT, 0);
}
params2.addRule(RelativeLayout.CENTER_IN_PARENT);
params2.addRule(RelativeLayout.BELOW, R.id.button_1); // place below button1
button2.setLayoutParams(params2);
}
});
So once you click on button2, it will move to below button1.
I'm having a difficulty adding buttons dynamically to a ScrollView. The code below is adding the buttons BUT there is no scroller.
If I'm putting the buttons directly in the XML (not dynamically) it's working and I can scroll down/up.
My view:
<ScrollView android:id="#+id/ScrollView01"
android:layout_width="264dp"
android:layout_height="match_parent"
android:fillViewport="true"
>
<LinearLayout
android:id="#+id/buttons"
android:layout_width="264dp"
android:layout_height="wrap_content"
android:orientation="vertical"
android:scrollbars="vertical"
>
** HERE THE BUTTONS SHOULD BE ADDED DYNAMICALLY **
</LinearLayout>
</ScrollView>
The code which adding buttons:
// create new button
final Button newbutton = new Button(this);
// set background color
newbutton.setBackgroundColor(Color.GRAY);
// set width and height
newbutton.setWidth(50);
newbutton.setHeight(20);
// set position
newbutton.setY(((float)numOfButton*20)+20);
newbutton.setX(100);
// set text
newbutton.setText(Integer.toString(numOfButton));
// create patameter
final LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT
);
//set listener
android.view.View.OnClickListener buttonListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// make all the DrawView invisible
for(View view : comments){
view.setVisibility(View.INVISIBLE);
}
// set the chosen comment visible
comments.get(numOfButton).setVisibility(View.VISIBLE);
boardsHandler.setCurrenBoard(numOfButton);
}};
newbutton.setOnClickListener(buttonListener);
// creating a thread to add button
buttons.post(new Runnable() {
#Override
public void run() {
buttons.addView(newbutton, p);
}
});
Is it something with the LinearLayout.LayoutParams p ?
Thanks!
Try following code
first do
LinearLayout myContainer = findViewById(R.id.layoutId);
When you set parameters for a view, they need to correspond to the parent view for your widget.
LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.FILL_PARENT);
finally add button as you are doing.
try and tell if it works
Setting X and Y position will not work. The LinearLayout layouts it's children vertically or horizontally, only taking their width/height into account.
Besides this -- have you tried calling buttons.invalidate() after buttons.addView(...). This should refresh the layout and should show your newbutton.
This is a rather old post but I found it quickly when doing research on that kind of problem. So I'll post am answer anyway, maybe it'll be of help to anyone..
I had a similar problem with a relative layout to which buttons were added dynamically. I found a workaround in defining the layout's size manually when adding the buttons. For your case, adding the line
buttons.getLayoutParams().height = numOfButton*20+40;
after
buttons.addView(newbutton, p);
might help, though it's probably not the best solution.
I thought my mistake was using the RelativeLayout at all, but since you appear to have the same problem...
Ever thought of using a table layout?
I want to nest a TableLayout inside a RelativeLayout and later dynamically edit the TableLayout in my Java Code.
My XML-File looks like this:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_load_date"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".LoadDateActivity" >
<!-- few buttons and textviews -->
<TableLayout
android:id="#+id/activity_load_date_table_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/button" >
</TableLayout>
</RelativeLayout>
Java Code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_load_date);
//Do something with my Buttons and TextViews(this works fine)
tblLayout = (TableLayout) findViewById(R.id.activity_load_date_table_layout);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.button_calc) {
for (int i = 0; i < listOfEntries.size(); i++) {
Entry temp = listOfEntries.get(i);
if (temp.getDate().getTime() >= startDate.getTime()
&& temp.getDate().getTime() <= endDate.getTime()) {
TableRow tr = new TableRow(this);
TextView comm = new TextView(this);
comm.setText(listOfEntries.get(i).getComment());
TextView val = new TextView(this);
val.setText(String.valueOf(listOfEntries.get(i).getValue()));
LayoutParams params = new LayoutParams(0,
LayoutParams.WRAP_CONTENT, 1f);
tr.setLayoutParams(params);
tr.addView(comm);
tr.addView(val);
tblLayout.addView(tr);
}
}
tblLayout.invalidate(); //Shouldn't this redraw the entire TableLayout and therefore adding my TableRows? This is not working.
}
}
Through various tests with TextViews and Toasts I have gathered that the tblLayout should be filled and the TableRows are added to the Layout, the only thing that is not working is the "repainting" of my Layout. How do I achieve that?
Edit:
Apparently the thing that made this not work was actually the LayoutParams given to the TableRow, once I commented those out I atleast got it printed to the screen. They are however not where I expect them to be.
I expected them to be below the buttons, instead they are in the top left corner on top of the buttons. This leads me to believe that the TableLayout is actually the same size as the RelativeLayout but is layered above the RelativeLayout. The error should therefor lie in my XML-File. What height do I need to give my TableLayout to make this work the way I expect?
Edit2:
I needed to add the android:layout_below attribute to my TableLayout, works as a charm now!
You need to call the method "requestLayout()"
Call this when something has changed which has invalidated the layout of this view. This will schedule a layout pass of the view tree.
I am using the following layout and want to add textviews one below another dynamically(depending on the data I want to display)
main.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="#+id/contain"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</LinearLayout>
</ScrollView>
So I tried this
public class Feeds extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent intent=getIntent();
Bundle b=intent.getExtras();
String s= b.getString("datapack");
Log.w("String",s);
String data[]=s.split("#");
String temp="";
LinearLayout l=(LinearLayout)findViewById(R.id.contain);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
(LayoutParams.WRAP_CONTENT), (LayoutParams.WRAP_CONTENT));
RelativeLayout relative = new RelativeLayout(getApplicationContext());
relative.setLayoutParams(lp);
for(int i=1;i<data.length;i++)
{Log.w("i data",data[i]);
temp=temp + data[i] + ",";
Log.w("tag",temp);
if(i%5==0)
{Log.w("data",temp);
TextView tv = new TextView(getApplicationContext());
tv.setLayoutParams(lp);
tv.setId(i);
tv.setText(temp);
relative.addView(tv, lp);
temp=null;
}
}
l.addView(relative);
}
}
I am using Scrollview for the first time so that is crating a bit of problem but the main problem is that the textviews in the relative layout overlap one another.How can I specify the gap between each view??
If you're adding views into a RelativeLayout you have to set where the view will be placed, different than LinearLayout that you only need to add the views inside there.
Trye to change to this
LinearLayout layout= new LinearLayout (getApplicationContext());
layout.setLayoutParams(lp);
And here you go a little tip. Do not do this
if(i%5==0)
{Log.w("data",temp);
try to do this
if(i%5==0){
Log.w("data",temp);
it's better to read and understand
I don't see where you are defining the positions for each textview, ie layout_below, layout_toLeftOf... If no positions are defined the relative layout stacks each view in the upper left corner.
Addition
It seems digulino and I agree. I would like to add that you should be able to get the layout scheme you want with only a RelativeLayout inside a ScrollView, maybe a HorizontalScrollView too if you want horizontal scrolling with fling gesture support.