Foobar
Foobar

Reputation: 8467

How to programmatically set Layout to Top and Start of screen?

You can set a LinearLayout to the top left of a screen by doing this:

  android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"

I was wondering how would I do this programmatically?

I have the following piece of code:

 LinearLayout btnBar = (LinearLayout) findViewById(R.id.btnBar);
    LinearLayout.LayoutParams btnBarParams = new LinearLayout.LayoutParams(screenWidth,screenHeight / 3);
 //Not sure how to set the layout to the top left.

but in LayoutParameters there is no addRule() method so I am not sure how to set these attributes. The LinearLayout is inside a RelativeLayout.

EDIT: I think I figured it out, but I am getting a exception. Here is my solution:

   LinearLayout btnBar = (LinearLayout) findViewById(R.id.btnBar);
    LinearLayout.LayoutParams btnBarParams = new LinearLayout.LayoutParams(screenWidth,screenHeight / 3);
    btnBarParams.gravity = Gravity.START;
    btnBar.setLayoutParams(btnBarParams);

But I cannot see if this is working because I get a exception on the last line of my solution saying

java.lang.ClassCastException: android.widget.LinearLayout$LayoutParams cannot be cast to android.widget.RelativeLayout$LayoutParams

Upvotes: 1

Views: 3048

Answers (2)

User0911
User0911

Reputation: 1582

This is how it will work,

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
params.weight = 1.0f;
params.gravity = Gravity.TOP;

btnBar.setLayoutParams(params);

Upvotes: 0

Foobar
Foobar

Reputation: 8467

The solution turned out to be using RelativeLayout.LayoutParams

 LinearLayout btnBar = (LinearLayout) findViewById(R.id.btnBar);
    RelativeLayout.LayoutParams btnBarParams = new RelativeLayout.LayoutParams(screenWidth,screenHeight / 3);
    btnBarParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
    btnBarParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
    btnBar.setLayoutParams(btnBarParams);

Upvotes: 2

Related Questions