程序化 android 评分栏绘制不正确

Programmatic android rating bar draws incorrectly

我正在尝试以编程方式创建评分栏。

如果我使用 XML 一切正常

<RelativeLayout 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"
android:id="@+id/derp">


<RatingBar
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:numStars="5"
    android:layout_centerHorizontal="true"
    />

结果是一个正常的、功能完美的评分栏,上面有红色的星星(我的强调色)。

但是如果我尝试以编程方式执行此操作:

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    LinearLayout l = new LinearLayout(getApplicationContext());
    l.setOrientation(LinearLayout.VERTICAL);
    l.setLayoutParams(new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT));

    RatingBar ratingBar = new RatingBar(getApplicationContext());

    ratingBar.setMax(5);
    ratingBar.setStepSize(1);
    ratingBar.setNumStars(0);

    l.addView(ratingBar);
    ((RelativeLayout)findViewById(R.id.derp)).addView(l);
}

结果完全不同。未选中的星星背景是看不见的,所以看起来像这样

Prog emprty

评级栏就在那里,如果您开始与之互动,它会正确显示

Prog interacting

一旦我移开手指,它就会变回一个不可见的未选中星星,但我选择的星星仍然正确突出显示。

星星的颜色也与 xml 不同。评级栏上下文构造函数使用的似乎是默认样式。 这在我的主应用程序中突然发生了,我真的不明白为什么。 我试图创建一个空的测试应用程序,但问题仍然存在。

有人知道可能是什么原因吗?

通常不应使用 applicationContext 来扩充视图,因为您的视图随后将使用系统的主题扩充,而不是应用程序中定义的主题。

尝试使用您的 activity 上下文。

 RatingBar ratingBar = new RatingBar(MainActivity.this);

要详细了解 context 的不同功能,请访问 very good article written by Dave Smith