[英]Changing background color dynamically (Android)
I have the following code: 我有以下代码:
public class MainActivity extends Activity {
private BufferedReader br;
private Socket s;
private View v,v1;
private RelativeLayout rl;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
s = new Socket("192.168.1.36",50000);
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
}catch(Exception e){e.printStackTrace();}
color();
}
private void color(){
rl = (RelativeLayout) this.findViewById(R.id.rellay);
while(true){
try{
String received = br.readLine();
if(received != null){
// System.out.println(received);
String[] color = received.split(",");
setColor(color);
}
}catch(Exception e){e.printStackTrace();}
}
}
private void setColor(String[] color){
rl = (RelativeLayout) this.findViewById(R.id.rellay);
int red = Integer.parseInt(color[0]);
int green = Integer.parseInt(color[1]);
int blue = Integer.parseInt(color[2]);
int a = Integer.parseInt(color[3]);
rl.setBackgroundColor(Color.argb(a, red, green, blue));
What I want to do is receive 4 values separated by commas (this works), and I want the values in the range 0-255 to be the RGB color. 我想要做的是接收用逗号分隔的4个值(这个工作),我希望0-255范围内的值是RGB颜色。
I want to change the background of the android activity. 我想改变android活动的背景。 I can change the color once, from the onCreate method, but when I try to change it further times I get the default white screen.
我可以从onCreate方法更改颜色一次,但是当我尝试更改它时,我会得到默认的白色屏幕。 The values never exceed 255.
值不会超过255。
How can this be done? 如何才能做到这一点? Thanks!!
谢谢!!
Make sure the alpha value != 0. The alpha value represent the transparency of the color so 0 is fully transparent. 确保alpha值!= 0. alpha值表示颜色的透明度,因此0是完全透明的。 try to start with fixed values, like:
尝试从固定值开始,例如:
rl.setBackgroundColor(Color.argb(255, 0, 0, 0));
and make sure it works. 并确保它的工作原理。 after that, pull your values from the server and parse them into a color.
之后,从服务器中提取值并将其解析为颜色。
BTW, Listen to Nick Cardoso comments, It's a bad user experience to feel the network latency. 听听Nick Cardoso的评论,感受网络延迟是一种糟糕的用户体验。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.