我试图以编程方式创建评级栏。
如果我使用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);
}
结果完全不同。未选择的恒星的背景是看不见的,因此看起来像这样。
评级栏在那里,如果你开始与它进行交互,它会正确显示
一旦我移开手指,它就会回到一个看不见的未选定的星星,但我选择的星星仍然正确突出显示。
星形颜色也不同于xml颜色。评级栏上下文构造函数使用的似乎是默认样式。 这突然发生在我的主应用程序中突然发生,我无法弄清楚原因。 我试图创建一个空的测试应用程序,问题仍然存在。
有人知道可能是什么原因吗?
答案 0 :(得分:1)
applicationContext
通常不应用于对视图进行充气,因为您的视图会因系统的主题而不是应用程序中定义的主题而膨胀。
尝试使用您的活动背景。
RatingBar ratingBar = new RatingBar(MainActivity.this);
要详细了解context
的不同功能,可以使用very good article written by Dave Smith