Reputation: 4093
I want to simply set the height of an EditText component to be 50% of the user's screen height.
I'm creating the initial layout from an xml file (main.xml), loaded in the Activity's onCreate(Bundle). From the xml configuration, I understand how to set the EditText height to a literal value, e.g., android:layout_height="150dip", and from the onCreate(Bundle), I understand that I can call setHeight(int) on the EditText component, but the call to setHeight(int) appears to be ignored, and if I don't have the layout_height setting in the xml, then I get an exception when my app is starting, complaining that the height value is required (and the app dies).
Is there a way to set the height from the xml based on the user's screen height? In other words, within the xml, is it possible to retrieve the user's screen height and use it to calculate a value for a component?
(I'm placing the EditText in a LinearLayout with vertical orientation.)
Upvotes: 2
Views: 8141
Reputation: 4093
Thank you for the replies. I figured something else out, instead.
In the xml, instead of specifying a literal numeric value, e.g. "200dip", for android:layout_height, and if just "fill_parent" is used, then the value set in the Activity with the call to setHeight(int) does not get ignored.
Though, I haven't yet looked up if this works by design or is just a glitch...
Upvotes: 0
Reputation: 11537
In Java you could try this:
package com.stackoverflow.q4274819;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;
public class Q4274819 extends Activity {
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DisplayMetrics metrics = new DisplayMetrics();
WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
wm.getDefaultDisplay().getMetrics(metrics);
final float height = metrics.heightPixels;
EditText e = (EditText) findViewById(R.id.edit);
e.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, (int) (height/2)));
LinearLayout l = (LinearLayout) findViewById(R.id.layout);
l.requestLayout();
}
}
Given a Layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<EditText android:id="@+id/edit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
</LinearLayout>
Upvotes: 0
Reputation: 77752
Use a linear layout, set the weight of the EditText to 1, then add another empty view and set its weight to 1 as well.
Upvotes: 5