以编程方式分配进度条样式Android

时间:2013-04-16 20:28:10

标签: android xamarin.android xamarin

我正在以编程方式生成滚动条,我已经定义了一种更改颜色的样式,所以我的问题很自然:如何设置滚动条的滚动条样式?

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);

当我尝试使用以下方法创建进度条后设置progressdrawable:

progressBar.ProgressDrawable = Resource.Drawable.myprogressbar;

我有:

  

无法将类型'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 个答案:

答案 0 :(得分: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);

修改 要将您自己的Drawable传递给progressBar.ProgressDrawable,您需要先加载它,就像您收到的错误所示。

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