【发布时间】:2020-03-13 04:55:59
【问题描述】:
我想要的是当我加载我的应用程序时,它可以从预定义的字符串列表中为每个 textview 随机设置特定颜色的背景。
@Override
protected void onCreate(Bundle savedInstanceState) {
int[] rainbow = getResources().getIntArray(R.array.rainbow);
int randomAndroidColor = rainbow[new Random().nextInt(rainbow.length)];
TextView lab = (TextView) findViewById(R.id.view1);
lab.setBackgroundColor(randomAndroidColor) super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
colors.xml
<resources>
<item name="blue" type="color">#FF33B5E5</item>
<item name="purple" type="color">#FFAA66CC</item>
<item name="green" type="color">#FF99CC00</item>
<integer-array name="rainbow">
<item>@color/blue</item>
<item>@color/purple</item>
<item>@color/green</item>
</integer-array>
为什么它不起作用?
更新 这是我的布局文件。 我的应用程序加载,但没有出现
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView
android:id="@+id/view1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<TextView
android:id="@+id/view2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<TextView
android:id="@+id/view3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
</LinearLayout>
【问题讨论】:
-
发布您的 xml 布局文件
-
@Prajwal 检查一下
-
使用给定的代码,您的应用程序应该会因
NullPointerException而崩溃。如果在setContentView()之前调用,findViewById()将返回 null。你确定那是你正在运行的实际代码吗?
标签: android random colors textview oncreate