Change the width of a ProgressBar added at runtime

前端 未结 3 1549
孤独总比滥情好
孤独总比滥情好 2020-12-16 04:41

I am building up a UI from code and can successfully add ProgressBar widgets, however I cannot alter the dimensions of the widget to values I need, it always stays at the de

相关标签:
3条回答
  • 2020-12-16 05:12

    R.layout.activity includes this:

    <ProgressBar
            android:id="@+id/progress"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:indeterminate="true"
            android:visibility="visible"
            style="@android:style/Widget.ProgressBar.Large.Inverse"
    />
    

    And then the code:

    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity);
        ProgressBar bar = (ProgressBar)findViewById(R.id.progress);
        bar.getLayoutParams().height = 500;
        bar.invalidate();
    }
    

    The call to the invalidate() method is important as that is when the view is redrawn to take the changes into account. Although unintuitive, it does allow for better performance by batching changes.

    0 讨论(0)
  • 2020-12-16 05:19

    So, you need to define your own style for the progress bar:

    <style name="SmallProgressBar" parent="android:Widget.ProgressBar">
        <item name="android:minHeight">10dip</item>
        <item name="android:maxHeight">35dip</item>
    </style>
    

    Here, you can set min and max height and width of the progress bar and other cool features.

    Now, you set in your xml layout style:

    <ProgressBar
        android:id="@+id/custom_edit_text_progress_bar"
        style="@style/SmallProgressBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentTop="true"
        android:visibility="visible"/>
    

    When you inflate your progress bar, you

    getLayoutParams().height = 25
    

    and

    getLayoutParams().width = 25
    

    for progress bar and set height and width.

    NOTE: You cannot exceed height and width that you defined in styles.

    0 讨论(0)
  • 2020-12-16 05:39

    There are minWidth/minHeight/maxWidth/maxHeight parameters as well, but (I think) they can only be set through XML or via a style/theme.

    Otherwise, you could inflate your ProgressBar view from XML.

    0 讨论(0)
提交回复
热议问题