以编程方式将ProgressBar添加到Android中的Fragment

时间:2016-11-20 01:17:49

标签: android android-fragments progress-bar

我能够在片段中操作现有TextView的一些文本。但是,我无法以编程方式将新ProgressBar添加到现有布局中 在Fragment类中:

 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_completed_office_hours, container, false);

        LinearLayout linearLayout = (LinearLayout) view.findViewById(R.id.linearLayoutCompletedOfficeHours);

        progressBar = new ProgressBar(this.getContext());
        progressBar.setMax(daysInTotal);
        progressBar.setProgress(daysCompleted);

        linearLayout.addView(progressBar);

        TextView textView = (TextView) view.findViewById(R.id.completedXOfYDays);
        textView.setText(daysCompleted + " / " + daysInTotal);
        return view;
    }

xml:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".fragment.CompletedOfficeHoursFragment">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="@dimen/activity_horizontal_margin"
        android:orientation="horizontal"
        android:id="@+id/linearLayoutCompletedOfficeHours">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/completedXOfYDays" />
    </LinearLayout>
</FrameLayout>

执行时,我将19 / 299作为文字,但没有任何ProgressBar。我做错了什么=

2 个答案:

答案 0 :(得分:0)

它没有显示,因为您没有指定其子项的layout_param,因此会导致父项不显示它。

您需要指定要附加的子视图的布局参数。

progressBar = new ProgressBar(this.getContext());
progressBar.setMax(daysInTotal);
progressBar.setProgress(daysCompleted);
progressBar.setLayoutParams(new LinearLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT));

答案 1 :(得分:0)

您已将“linearLayoutCompletedOfficeHours”指定为带有android:orientation="horizontal"和给定textview android:layout_width="match_parent"的线性布局。这将使textview占据整个空间并创建进度条并显示在屏幕上。 而是将textView宽度更改为android:layout_width="wrap_content",并且可以看到进度。

<TextView
   android:layout_width="wrap_content"
   android:layout_height="match_parent"
   android:id="@+id/completedXOfYDays" />
相关问题