RelativeLayout insert a view between two others - java

Let's say I have two buttons in a RelativeLayout. A button labeled "one" at the top and a button labeled "three" underneath "one". The layout is defined 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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:id="#+id/mainContainer"
tools:context=".MainActivity" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tvOne"
android:layout_centerHorizontal="true"
android:layout_alignParentTop="true"
android:text="One" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tvThree"
android:layout_centerHorizontal="true"
android:layout_below="#id/tvOne"
android:text="Three" />
</RelativeLayout>
So I wrote some code in the onCreate of MainActivity to dynamically create a Button, and insert it in between one and three. But it isn't working. Is there something I'm missing? I created this question as a simplified version of a bigger problem I'm having, so it's not acceptable for me to clear the layout and just insert one two and three dynamically.
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button one = (Button)findViewById(R.id.tvOne);
Button three = (Button)findViewById(R.id.tvThree);
//Dynamically create a button, set it underneath one and above two.
Button two = new Button(this);
two.setText("TWO TWO TWO TWO TWO TWO TWO");
//Create some layout params so that this button is horizontally centered,
//above button number three and below button number one
final int WC = RelativeLayout.LayoutParams.WRAP_CONTENT;
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(WC, WC);
params.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
params.addRule(RelativeLayout.BELOW, one.getId());
params.addRule(RelativeLayout.ABOVE, three.getId());
two.setLayoutParams(params);
//Add button number two to the activity.
RelativeLayout rl = (RelativeLayout)findViewById(R.id.mainContainer);
rl.addView(two);
}

Working code and I have checked this.
public class Main extends Activity {
Context ctx;
RelativeLayout rlayMainContainer;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ctx = this;
rlayMainContainer = (RelativeLayout) findViewById(R.id.mainContainer);
Button one = (Button) findViewById(R.id.tvOne);
Button three = (Button) findViewById(R.id.tvThree);
// adding button two dynamically
Button two = new Button(ctx);
two.setText("hello");
two.setId(12);
RelativeLayout.LayoutParams lpSecond = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lpSecond.addRule(RelativeLayout.CENTER_HORIZONTAL);
lpSecond.addRule(RelativeLayout.BELOW, one.getId());
rlayMainContainer.addView(two, lpSecond);
//align button three below button two
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) three
.getLayoutParams();
params.addRule(RelativeLayout.BELOW, two.getId());
three.setLayoutParams(params);
}
}

In fact, the "two" button is there, but you can not see it because its height = 0.
These lines of code make the "two" button's height = 0
params.addRule(RelativeLayout.BELOW, one.getId());
params.addRule(RelativeLayout.ABOVE, three.getId());
Yes, the "two" button layoutParams indicates that it must be between "one" and "three", but there is no space left between those buttons --> no height.
To solve this, you need to remove the line that set "two" is above "three" and add code to indicate that "three" is now below "two"
final int WC = RelativeLayout.LayoutParams.WRAP_CONTENT;
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
WC, WC);
params.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
params.addRule(RelativeLayout.BELOW, one.getId());
two.setLayoutParams(params);
// Add button number two to the activity.
RelativeLayout rl = (RelativeLayout) findViewById(R.id.mainContainer);
rl.addView(two);
two.setId(1);
params = (LayoutParams) three.getLayoutParams();
params.addRule(RelativeLayout.BELOW, two.getId());
three.setLayoutParams(params);

Related

Programmatically add an ImageView to Layout

I'm trying to add a bunch of ImageView on my UI using a loop, the problem is that I have no Idea if the ImageView is being added or not because when I run the app it just gives me a blank white screen.
for(int i = 0; i < jsonArray.length(); i++) {
Log.d("test", "ok"); //the loop works btw
poster.setId(i);
JSONObject jsonObject = jsonArray.getJSONObject(i);
ImageView poster = new ImageView(getApplicationContext());
poster.setBackgroundResource(R.drawable.myPoster);
RelativeLayout.LayoutParams posterParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
);
posterParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
posterParams.addRule(RelativeLayout.CENTER_VERTICAL);
posterParams.width = 160; //is this DP?
posterParams.height = 220;
relativeLayout.addView(poster, posterParams);
}
Any suggestion is welcome.
EDIT
I added another piece of code just to test if a widget will be added without using a loop:
//test
LinearLayout layout = new LinearLayout(this);
Button btn = new Button(this);
btn.setText("this is a button");
btn.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
layout.addView(btn);
And I still get the same result, just blank.
First of all, you are giving exactly the same parameter to each ImageView this causes all your ImageView lays on Like STACK only the last one will be visible to you. You may use ScrollView to see if the ImageViews actually added to your root layout
Secondly, set layout parameters to your dynamic ImageViews not your root layout.
Update
How to use ScrollView,
First of all, your XML should contain ScollView and a child (LinearLayout in our case but you can choose any layout depending on your use case) for placing your ImageView
<ScrollView>
<LinearLayout
android:id = "imageViewPlaceHolder">
</LinearLayout>
</ScrollView>
Secondly, in your Java code, you should find an inner layout to add views as follows
LinearLayout placeHolder = findViewById(R.id.imageViewPlaceHolder);
Then you are ready to add ImageViews into placeHolder since your placeHolder wrapped with ScrollView it will create a scroll dynamically if the content height goes beyond the dedicated height.
placeHolder.addView(yourImageView);
Adding everything from Java
HorizontalScrollView hsv = new HorizontalScrollView(context);
hsv.setLayoutParams(yourLayoutParams);
LinearLayout myPlaceHolder = new LinearLayout(context);
myPlaceHolder.setLayoutParams(yourLayoutParamsForLinearLayout);
myPlaceHolder.addView(yourDesiredImageView);
hsv.addView(myPlaceHolder);
yourRootLayout.addView(hsv);
Hope it makes sense, feel free to ask any clarification
try this:
listView = (ListView) findViewById(R.id.lv_info);
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, text);
listView.addHeaderView(creatHeader(getString(R.string.abuot_email),getResources().getString(R.string.email_info)));
listView.addHeaderView(creatHeader(getString(R.string.about_phone),getResources().getString(R.string.admin_phone_num)));
listView.addHeaderView(creatHeader(getString(R.string.about_copyright), getResources().getString(R.string.copyright_info)));
listView.addHeaderView(creatHeader(getString(R.string.about_version),getResources().getString(R.string.version_info)));
listView.setAdapter(adapter);
Method creatHeader:
public View creatHeader(String title, String text) {
View v = getLayoutInflater().inflate(R.layout.lv_item_header_info, null);
((TextView) v.findViewById(R.id.tvTitle)).setText(title);
((TextView) v.findViewById(R.id.tvText)).setText(text);
return v;
}
Layout file for items:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="#dimen/activity_vertical_margin">
<TextView
android:id="#+id/tvTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="ssss"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:gravity="center_vertical"/>
<TextView
android:id="#+id/tvText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="sssssssss"
android:gravity="center_vertical"/>
</LinearLayout>

Dynamically adding buttons next to each other - RelativeLayout

Ok, so here's the thing. I'm trying to make an app that resembles a piano for android, also I've never really had much experience with Java or programming for Android so all of this is pretty new to me. I've managed to do this in XML but I want to make it programmaticaly so I can easily add more white and black keys also dependant of screen size. In XML it looks like this
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="#+id/white1"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="#fff" />
<Button
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="#fff"
android:id="#+id/white2"
android:layout_toRightOf="#+id/white1"/>
<Button
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="#fff"
android:id="#+id/white3"
android:layout_toRightOf="#+id/white2"/>
<Button
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="#fff"
android:id="#+id/white4"
android:layout_toRightOf="#+id/white3"/>
<Button
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="#fff"
android:id="#+id/white5"
android:layout_toRightOf="#+id/white4"/>
<Button
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="#fff"
android:id="#+id/white6"
android:layout_toRightOf="#+id/white5"/>
<Button
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="#fff"
android:id="#+id/white7"
android:layout_toRightOf="#+id/white6"/>
<Button
android:layout_width="wrap_content"
android:layout_height="100dp"
android:layout_marginStart="-10dp"
android:layout_marginEnd="-6dp"
android:background="#000"
android:id="#+id/black1"
android:layout_toRightOf="#+id/white1"/>
<Button
android:layout_width="wrap_content"
android:layout_height="100dp"
android:layout_marginLeft="-6dp"
android:layout_marginRight="-10dp"
android:background="#000"
android:id="#+id/black2"
android:layout_toRightOf="#+id/white2"/>
<Button
android:layout_width="wrap_content"
android:layout_height="100dp"
android:layout_marginLeft="-10dp"
android:layout_marginRight="-6dp"
android:background="#000"
android:id="#+id/black3"
android:layout_toRightOf="#+id/white4"/>
<Button
android:layout_width="wrap_content"
android:layout_height="100dp"
android:layout_marginLeft="-8dp"
android:layout_marginRight="-8dp"
android:background="#000"
android:id="#+id/black4"
android:layout_toRightOf="#+id/white5"/>
<Button
android:layout_width="wrap_content"
android:layout_height="100dp"
android:layout_marginLeft="-6dp"
android:layout_marginRight="-10dp"
android:background="#000"
android:id="#+id/black5"
android:layout_toRightOf="#+id/white6"/>
And now I wanted to recreate it programmaticaly, at first I've tried linear approach but first of all I was unable to make more than 7 keys, and I didn't really knew how to make black keys on top of that. So now I've went with RelativeLayout and all is fine as long as I create two buttons, then it works fine, one is next to another. But when I try to create more than two buttons they kinda make a stack.
I was trying to make some sort of array of buttons so I could easily make a loop to create destined number of buttons. Also I wanted to change the width of buttons, so if I create 8 buttons the would have the width of screen_width/8 but I'm not quite sure if it makes any sense since it's actually not doing anything when uncommented.
I would be grateful for any tips :)
public class MainActivity extends AppCompatActivity {
final int[] whitelist = {R.id.whitebt1,R.id.whitebt2,R.id.whitebt3,R.id.whitebt4,R.id.whitebt5,
R.id.whitebt6,R.id.whitebt7,R.id.whitebt8};
Button[] whiteKeys = new Button[whitelist.length];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
final RelativeLayout pianoLayout = new RelativeLayout(this);
RelativeLayout.LayoutParams whiteKeyParams1 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
whiteKeys[0] = new Button(this);
whiteKeys[0].setId(View.generateViewId());
//whiteKeys[0].setHeight(height);
//whiteKeys[0].setWidth(width/8);
whiteKeys[0].setLayoutParams(whiteKeyParams1);
pianoLayout.addView(whiteKeys[0]);
whiteKeys[1] = new Button(this);
whiteKeys[1].setId(View.generateViewId());
//whiteKeys[i].setHeight(height);
RelativeLayout.LayoutParams whiteKeyParams2 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
whiteKeyParams2.addRule(RelativeLayout.RIGHT_OF, whiteKeys[0].getId() );
whiteKeys[1].setLayoutParams(whiteKeyParams2);
pianoLayout.addView(whiteKeys[1]);
//HERE'S IS THE MOMENT WHERE I TRY TO ADD THIRD BUTTON AND THE BUTTONS START TO PILE UP
/*
whiteKeys[2] = new Button(this);
whiteKeys[2].setId(View.generateViewId());
//whiteKeys[i].setHeight(height);
//RelativeLayout.LayoutParams whiteKeyParams2 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
whiteKeyParams2.addRule(RelativeLayout.END_OF, whiteKeys[1].getId());
whiteKeys[2].setLayoutParams(whiteKeyParams2);
pianoLayout.addView(whiteKeys[2]);*/
this.setContentView(pianoLayout);
}
}
You can add 8 same size buttons using weightsum and layoutweight with LienarLayout with horizontal orientations.
see below code it may help you to add same size buttons dynamically.
/* Add a new Linearlayout as a container for the buttons */
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.HORIZONTAL);
//Added Weight Sum 8 in LinearLayout
linearLayout.setWeightSum(8);
/* Create a new Buttons in this container, for the status bar */
//below LayoutParams define with weight 1 for buttons.
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, 1.0f);
Button button1 = new Button(linearLayout.getContext());
button1.setLayoutParams(param);
Button button2 = new Button(linearLayout.getContext());
button2.setLayoutParams(param);
Button button3 = new Button(linearLayout.getContext());
button3.setLayoutParams(param);
Button button4 = new Button(linearLayout.getContext());
button4.setLayoutParams(param);
Button button5 = new Button(linearLayout.getContext());
button5.setLayoutParams(param);
Button button6 = new Button(linearLayout.getContext());
button6.setLayoutParams(param);
Button button7 = new Button(linearLayout.getContext());
button7.setLayoutParams(param);
Button button8 = new Button(linearLayout.getContext());
button8.setLayoutParams(param);
With your approach before adding the view to parent layout you will have to add margins for every new key also which will prevent stacking one key over another.
params.setMargins(left, top, right, bottom);

Align TextView above EditText

I want to align a TextView above an EditText. The following code is working well when the TextView is not higher than the space between the Top Margin of the window (red line) and the EditText (green line), like in the screenshot.
The problem occurs when the TextView has more lines than in the screenshot: it just "overruns" the EditText, but I want to keep the EditText in foreground.
In other words: I would like to place the TextView's bottom margin onto the green line and let it grow towards the red line, in order to maintain the visibility of the EditText.
// LINEAR LAYOUT
LinearLayout layout = new LinearLayout(getApplicationContext());
layout.setOrientation(LinearLayout.VERTICAL);
setContentView(layout);
// TEXTVIEW
// how to set bottom margins programmatically?
layout.addView(tv);
// EDITTEXT
// place the EditText to the bottom of the layout, working well
et.setGravity(Gravity.BOTTOM);
et.setInputType(InputType.TYPE_CLASS_TEXT);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
params.gravity = Gravity.BOTTOM;
et.setLayoutParams(params);
layout.addView(et);
This should do it for you:
// LINEAR LAYOUT
LinearLayout layout = new LinearLayout(getApplicationContext());
layout.setOrientation(LinearLayout.VERTICAL);
setContentView(layout);
// TEXTVIEW
LinearLayout.LayoutParams paramstv = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT,1f);
tv.setLayoutParams(paramstv);
layout.addView(tv);
// EDITTEXT
et.setGravity(Gravity.BOTTOM);
et.setInputType(InputType.TYPE_CLASS_TEXT);
LinearLayout.LayoutParams etparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT,8f);
etparams.gravity = Gravity.BOTTOM;
et.setLayoutParams(etparams);
layout.addView(et);
I guess the key is really to wrap both the EditText and TextView into LayoutParams. Probably you have to adjust the weights.
If this one doesn't work, try to create your layout with an XML file (the handling there is easier).
Try using the relative layout instead and set the edittext at the parent's bottom..
In case you don't want to switch to relative layout then try declaring edit text before the text view..
You can set the property of EditText type to textMultiline.
As you're using LinearLayout , set weight for your views
LinearLayout.LayoutParams paramTextView = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT, 1.0f);
tv.setlayoutParams(paramTextView);
LinearLayout.LayoutParams paramEditText = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT, 3.0f);
et.setlayoutParams(paramEditText);
This shall give you the result you expect
This below xml code can solve your problem...
<RelativeLayout
android:layout_height="match_parent"
android:layout_width="match_parent">
<SrollView
android:layout_height="match_parent"
android:layout_width="match_parent"
android:layout_above="#+id/edittext_id"
android:layout_margin="7dp">
<TextView
android:id="#+id/text_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</SrollView>
<EditText
android:id="#+id/edittext_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_alignParentBottom="true"/>
</RelativeLayout>

How do I make an ImageButton to randomly be positioned within a linear layout? (Android)

I have a linear layout with a certain amount of padding. I want an image button to be placed randomly anywhere within that linear layout without going outside the layout. Here is my xml code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="45dp"
android:text="Text 1"
android:id="#+id/text1" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="30dp"
android:text="Text 2"
android:id="#+id/text2" />
<LinearLayout
android:id="#+id/lay1"
android:layout_width="match_parent"
android:layout_height="450dp"
android:layout_margin="20dp">
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:src="#drawable/ib"
android:id="#+id/button1"/>
</LinearLayout>
</LinearLayout>
I want the ImageButton button1 to be placed randomly within layout lay1.
I have tried getting the width and height of the layout and feeding them into a random function which I then use to provide a left margin and top margin to the imagebutton, but my app keeps crashing whenever I do that. Here's the Java code:
ImageButton b = (ImageButton) findViewById(R.id.button1);
LinearLayout l = (LinearLayout) findViewById(R.id.lay1);
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) b.getLayoutParams();
int width = l.getWidth();
int height= l.getHeight();
params.leftMargin = new Random().nextInt(width);
params.topMargin = new Random().nextInt(height);
b.setLayoutParams(params);
The above method did not work and my app always crashes when I open this activity. Can someone please help me out?
Your method looks good, but you also have to take into account the image size.
So I'd put something like :
params.leftMargin = new Random().nextInt(width - b.getWidth());
params.topMargin = new Random().nextInt(height - b.getHeight());
Now you're gonna have to be more specific about the crash you're experiencing.
EDIT : Also SnyersK is right, if you're going through that piece of code before the element got their dimensions, then you'll need to use a ViewTreeObserver.
I've got a partial solution for you.
The following code places a button at a random location BUT it can be put off screen. You should be able to prevent this by playing around with the random generator.
public class MainActivity extends ActionBarActivity {
int width, height;
LinearLayout linearLayout;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
linearLayout = (LinearLayout) findViewById(R.id.ll);
linearLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
Log.v(getClass().getSimpleName(), "onGlobalLayout");
width = linearLayout.getWidth();
height = linearLayout.getHeight();
placeButton();
if (Build.VERSION.SDK_INT >= 16) {
linearLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
} else {
linearLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
}
});
button = (Button) findViewById(R.id.button);
}
private void placeButton() {
Log.v(getClass().getSimpleName(), "width: " + width + " Height: " + height);
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) button.getLayoutParams();
Random rand = new Random();
params.leftMargin = rand.nextInt(width);
params.topMargin = rand.nextInt(height);
Log.v(getClass().getSimpleName(), "left: " + params.leftMargin + " top: " + params.topMargin);
button.setLayoutParams(params);
button.invalidate();
}
}
You just wait for your linearlayout to be drawn. Then you get it's width and height and put the button on a random place.
Note
This will move the button around when you rotate the screen. you could prevent this by only adding an OnGlobalLayoutListener if savedInstanceState == null
Just replace your code with this
ImageButton b = (ImageButton) findViewById(R.id.button1);
LinearLayout l = (LinearLayout) findViewById(R.id.lay1);
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)l.getLayoutParams();
int width = l.getWidth();
int height= l.getHeight();
params.leftMargin = new Random().nextInt(width);
params.topMargin = new Random().nextInt(height);
l.setLayoutParams(params);

Buttons in linearlayout appearing vertically instead of horizontally?

I'm very new to Android and I'm trying to dynamically add buttons in my android app, the problem is that they appear vertically, while this should be horizontally.
What I'm getting:
What I'm expecting (and want):
Code I'm using:
MainActivity.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout ll = (LinearLayout)findViewById(R.id.main_linearlayout);
for(int x = 1; x <= 5 ; x++)
{
LinearLayout tmpLinearLayout = new LinearLayout(this);
tmpLinearLayout.setOrientation(LinearLayout.VERTICAL);
tmpLinearLayout.setLayoutParams( new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT, 1.0f));
tmpLinearLayout.getLayoutParams().height = 200;
ll.addView(tmpLinearLayout);
for(int i = 0;i<5;i++)
{
Button tmpButton = new Button(this);
tmpButton.setText("nr:" + i +" - " + x);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, 1.0f);
tmpLinearLayout.addView(tmpButton, lp);
}
}
}
Layout (activity_main.xml):
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:id="#+id/main_linearlayout"
android:layout_height="match_parent"
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"
android:background="#drawable/background"
android:orientation="horizontal" >
</LinearLayout>
Can anyone explain why it does this/correct me?
Thank you!
You're programmatically setting vertical orientation.-
Replace this line
tmpLinearLayout.setOrientation(LinearLayout.VERTICAL);
with this one
tmpLinearLayout.setOrientation(LinearLayout.HORIZONTAL);
PS: As far as I know, Horizontal is the default orientation, so you actually could just delete the orientation line.
Change the android:orientation to vertical in your xml layout.

Categories

Resources