对不起,我的英语不好,我是android的初学者,现在我被卡住了。
现在我的问题是如何使用OnClickListener
将随机颜色设置为背景。您可以帮我解决这个问题吗?
我有一堂课(Kleurenpalet.java)
package com.example.pstek.randomcolor;
import android.graphics.Color;
import java.util.Random;
public class Kleurenpalet{
private static String[] kleur = {
"#39add1", // light blue
"#3079ab", // dark blue
"#3FD52D", // green
"FFFF0000", // red
""};
public int getRandomColor() {
Random rand = new Random();
int color = rand.nextInt(kleur.length);
return Color.parseColor(kleur[color]);
}
}
我有我的主要班级:
package com.example.pstek.tegeltjeswijsheid;
import android.support.constraint.ConstraintLayout;
import android.support.constraint.solver.widgets.ConstraintWidget;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Layout;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
private ConstraintLayout layout;
private Button randombutton;
int randomColor = new Kleurenpalet().getRandomColor();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
layout = findViewById(R.id.layout);
randombutton = findViewById(R.id.button);
randombutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
layout.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), ;
}
});
}
}
答案 0 :(得分:0)
也许用初始化的颜色调用setBackgroundColor
:
layout.setBackgroundColor(randomColor);
或者每次都不一样:
layout.setBackgroundColor(new Kleurenpalet().getRandomColor());
答案 1 :(得分:0)
我不明白您在这里尝试做什么:
@Effect({ dispatch: false })
updatePresentation$ = this.actions$.pipe(
ofType(UpdateComponentPresentation),
map((action) => {
const someComponentId = action.payload.id;
const service1 = getComponentServiceInstanceById(id);
this.service.rerender();
})
);
您为什么在那里留空?此外,如果您解析layout.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), ;
中的颜色,则必须不使用Kleurenpalet
。只需这样设置颜色:
ContextCompat
layout.setBackgroundColor(randomColor);
是用于解析资源文件中的颜色,例如:
ContextCompat
答案 2 :(得分:0)
在MainActivity代码中:
public class MainActivity extends AppCompatActivity {
private ConstraintLayout layout;
private Button randombutton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
layout = findViewById(R.id.layout);
randombutton = findViewById(R.id.button);
randombutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int randomColor = new Kleurenpalet().getRandomColor();
layout.setBackgroundColor(randomColor);
}
});
}
}
答案 3 :(得分:0)
您必须在按钮单击事件中放入“随机数字”和“布局设置颜色”:
randombutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int randomColor = new Kleurenpalet().getRandomColor();
layout.setBackgroundColor(randomColor);
}
});