簡體   English   中英

如何更改進度條的大小(寬度和高度)以適合所有線性布局?

[英]How to change the size (width and height) of progressbar to fit all in linearlayout?

我想向線性布局添加未知數量的進度條。 (如 Whatsapp 狀態和 Instagram 故事)我可以將進度條添加到線性布局,但進度條只顯示最多 7 個進度條。 帶有 7 個進度條的進度條,即使應該是 10

到目前為止我的代碼:

while (i < 10){
    i ++;
    View child = getLayoutInflater().inflate(R.layout.stories_progress, null);
    linearLayout.addView(child);
}

我想以編程方式縮小進度條的大小,所以當我有 2 個進度條時,它們會以 50%/50% 填充布局,當 5、10 甚至 20 個進度條時,它們會變小,它們都會顯示在線性布局我試圖獲取線性布局的當前寬度並除以進度條的數量,但線性布局的寬度總是返回0;

我的 xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/linear_layout_id"
    android:layout_width="match_parent"
    android:layout_height="30dp"
    android:orientation="horizontal"
    tools:context=".stories">

</LinearLayout>

我的進度條

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="5dp">

    <ProgressBar
        android:id="@+id/stories_progressBar_id"
        style="@style/Widget.AppCompat.ProgressBar.Horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </ProgressBar>

</LinearLayout>

您可能沒有等待頂部的LinearLayout具有大小。 您可以等待使用ViewTreeObserver.OnGlobalLayoutListener分配大小。 這是一些應該有幫助的代碼:

linearLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        linearLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this);

        linearLayout.removeAllViews();
        int newWidth = linearLayout.getWidth() / 10;
        int newHeight = linearLayout.getHeight();
        int i = 0;
        while (i < 10) {
            i++;
            LinearLayout child =
                    (LinearLayout) getLayoutInflater().inflate(R.layout.stories_progress,
                            linearLayout, false);
            LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) child.getLayoutParams();
            lp.width = newWidth;
            lp.height = newHeight;
            linearLayout.addView(child);
        }
    }
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM