简体   繁体   中英

how to call a method from layout xml android

i want to get the width size of the device and put it into "android:layout_width"

i tried to do this:

android:layout_width="GetSizeOfDevice()"

but it doesnt work... how can i call a method from the layout xml?

by the way, GetSizeOfDevice() do:

Display display = getWindowManager().getDefaultDisplay();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2)
{
    Point size = new Point();
    display.getSize(size);
    int width1 = size.x;
    return width1/4;
}
else
{
    int width1 = display.getWidth();
    return width1/4;
}

You guys might be missing the obvious ... if you're just going to get the width and populate the field with it then why not use layout_width="fill_parent"? The only place you can call a method from within the layout file is android:onClick="doSomething()" and I would highly discourage that.

you can't call java methods from xml layout.

what you are trying to do can be easily achieved by using layout weightSum/weight attributes.

just set weightSum for your view's parent layout group (Linearlayout, framelayout ...) like this :

android:WeightSum="4"

and for your view set:

android:Weight="1"
andrpod:layout_width="wrap_content"

then the view will automatically scale to 1/4th of your screen width

This is how you get the width:

// getting the width of the display
Context context = getActivity().getBaseContext();
WindowManager window = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = window.getDefaultDisplay();
final int width = display.getWidth();


Then you set your new width by using .setWidth() :

yourView.setWidth(width);


I have tested this and it works . There's no need to call a method from within the layout, as Bill Mote pointed out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM