How to get width of the Button in android
I want to show EditText
and Button
in one line. But the size of the button is the fixed to some pixels. I wanted to get the width of Button
programatically so that i can adjust width of EditText
on changing the orientation to vertical or horizontal my XML file is as follows
<LinearLayout
android:id="@+id/middleLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
>
<EditText
android:layout_height="50px"
android:layout_width="wrap_content"
android:id="@+id/searchBox"
android:layout_marginTop="2px"
android:visibility="visible"
android:singleLine="true"
android:hint="Enter Zip Code, City & State"
/>
<Button
android:layout_height="wrap_content"
android:layout_width="20px"
android:id="@+id/searchBtn"
android:visibility="visible"
android:layout_marginTop="3px"
android:text="Search"
/>
</LinearLayout>
I am calculating it by following code.
searchBox = (EditText) findViewById(R.id.searchBox);
searchbutton = (开发者_运维技巧Button) findViewById(R.id.searchBtn);
int searchIconWidth = searchbutton.getWidth();
searchBox.setWidth(getting_screen_width() - searchIconWidth );
for calculating screen width I have used following
private int getting_screen_width()
{
DisplayMetrics dm = null;
dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
String width = ""+dm.widthPixels ;
dm = null;
return Integer.parseInt(width);
}
But when I run above code than EditText
takes full width & Search button is not shown. What can be the problem in getting the Button width in Pixels.
Please help me out. Thanks in advance.
Perhaps you would want to use a different layout for landscape. Check this link.
Basically you can have a second layout for landscape creating a new folder in the /res/
path called layout-land
. Place there your new layout with the same name and Android will take care of the rest.
You need to put the same code in onResume()
as when this gets call you will get all the components placed already and can be rearranged.
just a small change in code due to deprecation.
Change from
android:layout_width="fill_parent"
android:layout_height="fill_parent"
to
android:layout_width="match_parent"
android:layout_height="match_parent"
精彩评论