【问题标题】:Randomly change background color on button click?单击按钮时随机更改背景颜色?
【发布时间】:2014-10-07 08:27:33
【问题描述】:

这是我的代码:

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my_activity2);
    Button n = (Button) findViewById(R.id.button);
    Typeface typeface = Typeface.createFromAsset(getAssets(), "BebasNeue Bold.ttf");
    n.setTypeface(typeface);
    final TextView tv = (TextView) findViewById(R.id.textView);
    Typeface face = Typeface.createFromAsset(getAssets(),
            "OSP-DIN.ttf");
    tv.setTypeface(face);


    final String[] values = getResources().getStringArray(R.array.things_array);
    n.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Random RAND=new Random();
            String nextValue = values[RAND.nextInt(values.length)];
            tv.setText(nextValue);
        }
    });
}

我也有这个:

<string-array name="colorcode_array">
<item>3498db</item>
<item>2ecc71</item>
<item>9b59b6</item>
<item>f1c40f</item>
<item>1abc9c</item>
<item>2980b9</item>
<item>8e44ad</item>
<item>e41c1c</item>
<item>2ecca9</item>
<item>752ecc</item>
<item>4f2ecc</item>
<item>2eccc3</item>
<item>2ecc53</item>
<item>2ecc2e</item>
<item>5bcc2e</item>
<item>9ecc2e</item>
<item>cca12e</item>
<item>cc712e</item>
<item>f1c209</item>
<item>86f109</item>
<item>f11616</item>
<item>9c1818</item>
</string-array>

现在我需要的是,在单击按钮的那一刻,您可以看到按钮已经从 things_array 随机加载文本到 textview 中,但同时我希望背景颜色通过使用颜色随机更改colorcode_array 中的代码。

我该怎么做?

【问题讨论】:

    标签: android


    【解决方案1】:

    view.setBackgroundColor(Color.parseColor("#"+array[index])); 应该为你做 :)

    (您的情况:view = tvarray[index] = nextValue

    【讨论】:

    • 这可行,但我希望字符串数组中的所有颜色按随机顺序排列
    • 这正是我的意思。 string = "#"+array[index]
    • 对不起我的菜鸟......所以像这样:#+colorcode_array[index] ?
    • 当然你需要有tv而不是view和"#"+nextValue而不是"#"+array[index]
    • 当我点击按钮时它崩溃了。是不是因为那个onclick方法中的数组是things_array,它是文本而不是颜色代码,并且因为tv是textview,而textview没有背景颜色?
    猜你喜欢
    • 2014-10-09
    • 2017-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-10
    • 1970-01-01
    • 2019-04-14
    相关资源
    最近更新 更多