Question

I am using ProgressBar as a part of Custom ListView. Now, I want to display ProgressBar's Width as per the value of ProgressBar and that is based on screen.

For i.e. If progress Value is 100 then it should show its width 100% of the device screen and like that for all 0-100 values.

My Code is as below :

layout.xml :

<ProgressBar
    android:id="@+id/pbTopicAccuracy"
    style="?android:attr/progressBarStyleHorizontal"
    android:layout_width="fill_parent"
    android:layout_height="20dp" />

<TextView
    android:id="@+id/tvAccuracy"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@id/pbTopicAccuracy"
    android:layout_alignLeft="@id/pbTopicAccuracy"
    android:layout_alignTop="@id/pbTopicAccuracy"
    android:paddingLeft="5dp"
    android:textColor="@color/black"
    android:textSize="12sp" />

Java Code :

adapter.setViewBinder(new SimpleAdapter.ViewBinder() {

@Override
public boolean setViewValue(View view, Object data, String textRepresentation) {

    if (view.getId() == R.id.pbTopicAccuracy) {
        int value = Integer.parseInt(data.toString());
        ((ProgressBar) view).setProgress(value);

        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(value, 30);
        ((ProgressBar) view).setLayoutParams(params);
    }

} });

It is working fine but It is not setting width as per it should be. If value is 100 then it sets width around like 4.5 part of the device screen. I think I will need to convert value to dp, then don't know.

How to prevent this problem and get proper width ?

Was it helpful?

Solution

Try Like this,

Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
 int ratio = ((int) display.getWidth() /100) * value ;
 ((ProgressBar) view).setProgress(ratio);
 // float ratioDp = convertPixelsToDp(ratio);
 // ((ProgressBar) view).setProgress(ratioDp);

Still not fill with device with convert the px value to dp using this function, and use the commented lines

public static float convertPixelsToDp(int px){
    Resources resources = context.getResources();
    DisplayMetrics metrics = resources.getDisplayMetrics();
    float dp = px / (metrics.densityDpi / 160f);
    return dp;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top