简体   繁体   中英

How to set layout params to units dp 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.

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));

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()
);

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));
int dp1 = dip2pix(getContext(), 1);
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
            dp1 * 100, ViewGroup.LayoutParams.WRAP_CONTENT);

public static int dip2pix(@NonNull Context context, int dip) {
    return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip,
            context.getResources().getDisplayMetrics());
}

Give it a try it will work for sure

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                200, 200);
        params.setMargins(5, 0, 5, 0);

        mChart= new HorizontalBarChart(getApplicationContext());
        mChart.setLayoutParams(params);

        mainLayout.addView(mChart);

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