Reputation: 309
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;
}
Upvotes: 1
Views: 2119
Reputation: 1320
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.
Upvotes: 0
Reputation: 12823
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.
Upvotes: 1
Reputation: 9286
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
Upvotes: 0