Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set layout params to units dp android

Tags:

android

mainLayout = (LinearLayout) findViewById(R.id.linearLayout);
mChart = new HorizontalBarChart(this);
mChart.setLayoutParams(new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT));
mainLayout.addView(mChart);

I like to change the width and height to dp units like 100 dp or 200 dp,. the setLayoutParams doesn't take number units , the choices are only (wrap_content and match_content).. I'm new to Android so im confused how to change it.

like image 520
Ruby Avatar asked Feb 12 '16 02:02

Ruby


3 Answers

Another ways is you add your dimension in dimens.xml.

For example, add <dimen name="chart_width">100dp</dimen>.

Then, at your code:

float width = getResources().getDimension(R.dimen.chart_width);
mChart.setLayoutParams(new ViewGroup.LayoutParams(
            width,
            ViewGroup.LayoutParams.WRAP_CONTENT));
like image 95
Joey Chong Avatar answered Oct 18 '22 03:10

Joey Chong


Converting dip values into pixels will let your layout build correctly, this line of code will solve it:

int width = (int) TypedValue.applyDimension(
    TypedValue.COMPLEX_UNIT_DIP, 
    getResources().getDimension(R.dimen.desired_width), 
    getResources().getDisplayMetrics()
);
like image 38
blueware Avatar answered Oct 18 '22 04:10

blueware


I think we can't set dp directly to the view. So we've to convert the dimension from pixel to dp.

To get pixel from dp, you can use TypedValue#applyDimension() method.

Resources r = getResources();
float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, {sizeInDp}, r.getDisplayMetrics());

So the final code will be

float width = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, {widthInDp}, r.getDisplayMetrics());

float height = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, {heightInDp}, r.getDisplayMetrics());

mChart.setLayoutParams(new ViewGroup.LayoutParams(
                width,
                height));
like image 34
theapache64 Avatar answered Oct 18 '22 04:10

theapache64