Reputation: 3165
I'm trying to get linearlayout's size.
I tested as following code.
But I just get value -1 (linearlayout's width).
How to get correct size?
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mainLayout"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello World, MyActivity"
/>
</LinearLayout>
package com.example.LayoutSize;
import android.app.Activity;
import android.os.Bundle;
import android.view.ViewGroup;
import android.widget.LinearLayout;
public class MyActivity extends Activity {
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.mainLayout);
ViewGroup.LayoutParams layoutParams = linearLayout.getLayoutParams();
System.out.printf("linearLayout width : %d", layoutParams.width);
}
}
Upvotes: 0
Views: 49
Reputation: 7698
The reason you get -1
is because the width
parameter is set to MatchParent
which has a value -1
.
To get the size of a layout, your should be using getWidth()
or getMeasuredWidth()
methods. However, these methods won't give you a meaningful answer until the view has been measured. Read about how android draws views here.
You can get the correct size, by overriding the onWindowFocusChanged()
as mentioned in this thread.
Alternatively, (hacky solution), you could do this:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final LinearLayout linearLayout = (LinearLayout) findViewById(R.id.mainLayout);
linearLayout.post(new Runnable() {
@Override
public void run() {
System.out.printf("linearLayout width : %d", linearLayout.getMeasuredWidth());
}
});
}
Upvotes: 1