views:

65

answers:

1

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 &amp; 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 advanced.

A: 

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.

Macarse
you are right, but my problem is, when I am trying to print the width of button, it shows me 0 in Logcat. so the EditText is taking full screen. I wondering about width given in xml to that button is treated as 0px in program.
Ashay
Where are you placing that Log line?
Macarse
I'm printing value of searchIconWidth variable. I have don that in my debugging part not posted here.Log.d("ButtonWidth",""+searchIconWidth);But you can place after this lineint searchIconWidth = searchbutton.getWidth();
Ashay
@Ashay: Sorry, I am willing to know if you place it `onCreate()`, `onStart()`. I guess you should place it `onStart()`.
Macarse
I am placing it in onCreate()
Ashay
@Ashay: Plz try placing it `onStart()` just to be sure.
Macarse
Ashay
The view isn't drawn yet on oncreate or onstart. You have to check for the width AFTER the view is drawn.
Falmarri