2016-11-20 61 views
0

我能夠操縱片段中現有TextView的一些文本。但是,我無法以編程方式將新的ProgressBar添加到現有佈局。
片段中的類:以編程方式將進度條添加到Android中的片段中

@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。我在做什麼錯=

回答

0

它沒有顯示,因爲你沒有指定它的孩子的layout_param,因此會導致父母不顯示它。

您需要指定要附加的子視圖的佈局參數。

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

不幸的是,這並沒有解決它 –

0

已指定「linearLayoutCompletedOfficeHours」作爲一個線性佈局與android:orientation="horizontal"和給定的TextView android:layout_width="match_parent" .Making這將使TextView的拿整個空間和進度被創建並在屏幕上顯示。 改爲將textView寬度更改爲android:layout_width="wrap_content",並且進度將可見。

<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="match_parent" 
    android:id="@+id/completedXOfYDays" /> 
相關問題