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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With