Gustavo Serna Gustavo Serna - 6 months ago 81
Android Question

Android - set width percentage to an editText inside a relativeLayout programatically

I have an editText inside a relativeLayout and I want that the width of the editText goes to the 70% of the total width of the relativeLayout, how can I achieve this? without using a LinearLayout


PercentRelativeLayout is recommended for your purpose.

But if you still want to use RelativeLayout and change the percentage in code, you can compute the width and set it to your EditText like this:

editText.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    public void onGlobalLayout() {

        ViewGroup.LayoutParams params = editText.getLayoutParams();
        params.width = (int) (relativeLayout.getWidth() * 0.7 + 0.5);

Hope this can help you.