2013-04-16 45 views
0

我以編程方式生成滾動條,並且定義了一種樣式來確定顏色,所以我的問題很自然:如何設置滾動條的滾動條樣式?以編程方式分配進度條樣式android

ProgressBar progressBar = new ProgressBar(this, null, Android.Resource.Attribute.ProgressBarStyleHorizontal); 
// I tried ProgressBar progressBar = new ProgressBar(this, null, Android.Resource.Drawable.myprogressbar); but it doesn't work 
    progressBar.Progress = 25; 
    linearLayout.AddView(progressBar); 

的我的風格的路徑是android:attr/progressBarStyleHorizontal所以我怎麼能這樣?

的XML代碼(即要通過程序取得)是:

<ProgressBar 
     style="?android:attr/progressBarStyleHorizontal" 
     android:progressDrawable="@drawable/myprogressbar" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:id="@+id/progressBar1" 
     android:progress="50" 
     android:startColor="#ffffff" 
     android:endColor="#ff1997e1" /> 

編輯:

我把

ProgressBar progressBar = new ProgressBar(this, null, Resource.Drawable.myprogressbar); 

但現在沒有欄出現在應用程序: - (

編輯:

我已經測試過的代碼,並沒有再次出現:

var progressBar = new ProgressBar(this, null, Resource.Drawable.myprogressbar) 
       { 
        Progress = 25, 
        LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FillParent, ViewGroup.LayoutParams.WrapContent), 
       };     
       linearLayout.AddView(progressBar); 

當我嘗試使用

progressBar.ProgressDrawable = Resource.Drawable.myprogressbar; 

設置進度創建後progressdrawable我

無法將類型'int'隱式轉換爲 'Android.Graphics.Drawables .Drawable」。一個顯式轉換存在 (是否缺少強制轉換?)

最後編輯:

這是我的最後一個碼:

// progressbar with custom style (Resources/Drawable/myprogress.xml) 
        ProgressBar progressBar = new ProgressBar(this, null, Android.Resource.Attribute.ProgressBarStyleHorizontal) 
        {LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FillParent, ViewGroup.LayoutParams.WrapContent)}; 
        progressBar.ProgressDrawable = Resources.GetDrawable(Resource.Drawable.myprogressbar); 
        // Compute for the percent of this usage (to assign it to the progressbar) 
      progressBar.Progress = 33; 
        linearLayout.AddView(progressBar); 

回答

1

ProgressBar沒有顯示,因爲你忘了設置LayoutParameters。以下代碼適用於我。我嘗試過各種ProgressBar款式。

var myLinearLayout = FindViewById<LinearLayout>(Resource.Id.myLinearLayout); 

var progressBar = new ProgressBar(this, null, Android.Resource.Attribute.ProgressBarStyleLarge) 
    { 
     Progress = 25, 
     LayoutParameters = 
      new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FillParent, ViewGroup.LayoutParams.WrapContent) 
    }; 

myLinearLayout.AddView(progressBar); 

編輯: 要通過自己的DrawableprogressBar.ProgressDrawable您需要先加載它,就像你的錯誤指示。

progressBar.ProgressDrawable = Resources.GetDrawable(Resource.Drawable.myprogressbar); 
+0

@Cheesnaron:你的代碼maked我傳統的進度,但這個想法是用做我自定義的進度(至極工作在XML) – clement

+1

見我的編輯,它顯示瞭如何加載'Drawable'。 – Cheesebaron