我创建了一个应用程序,假设每次点击都会切换按钮背景颜色。这是代码:
package com.example.flash.light;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button screen = (Button) findViewById(R.id.screen);
Drawable background = getResources().getDrawable(R.drawable.black);
screen.setBackgroundDrawable(background);
screen.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v) {
Button screen = (Button) findViewById (R.id.screen);
Drawable background = screen.getResources().getDrawable(screen.getId());
if(background == getResources().getDrawable(R.drawable.black)){
Drawable newBackgroun = getResources().getDrawable(R.drawable.white);
screen.setBackgroundDrawable(background);
}
if(background == getResources().getDrawable(R.drawable.white)){
Drawable newBackgroun = getResources().getDrawable(R.drawable.black);
screen.setBackgroundDrawable(background);
}
}
});
}
点击按钮不响应。 感谢
答案 0 :(得分:2)
我相信这里的问题是你的
返回的资源getResources().getDrawable(int id)
每次调用它时,都不同。 Android只是构造了drawable类的新实例,而不是返回旧的实例。 (至少我相信在这种情况下没有缓存)
使用==运算符比较三个不同的实例将永远不会返回true。
第二件事是代码中的一个明显错误:
Button screen = (Button) findViewById (R.id.screen);
Drawable background = screen.getResources().getDrawable(screen.getId());
if(background == getResources().getDrawable(R.drawable.black)){
Drawable newBackgroun = getResources().getDrawable(R.drawable.white);
screen.setBackgroundDrawable(**newBackground**);
}
if(background == getResources().getDrawable(R.drawable.white)){
Drawable newBackgroun = getResources().getDrawable(R.drawable.black);
screen.setBackgroundDrawable(**newBackground**);
}
而不是背景你应该有newBackground。
答案 1 :(得分:1)
试试这个:
public class MainActivity extends Activity {
private boolean isBlack = false;
@Override
public void onCreate(Bundle savedInstanceState) {
// your code
final Button screen = (Button) findViewById (R.id.screen);
isBlack = true;
screen.setBackgroundColor(Color.BLACK);
screen.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v) {
if (isBlack){
screen.setBackgroundColor(Color.WHITE);
isBlack = false;
}
else{
screen.setBackgroundColor(Color.BLACK);
isBlack = true;
}
}
});
}
}