gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 01:32:31 25 4
gpt4 key购买 nike

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

如果我使用 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 通常不应该用于扩充 View ,因为您的 View 随后会被系统的主题扩充,而不是应用程序中定义的主题。

尝试使用您的 Activity 上下文。

 RatingBar ratingBar = new RatingBar(MainActivity.this);

要了解有关不同context 功能的更多信息,请访问 very good article written by Dave Smith

关于android - 程序化的 android 评分栏绘制不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35554914/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com