import android.app.Activity;
import android.graphics.Color;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
private Button buton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buton = (Button) findViewById(R.id.buton_verde);
View.OnClickListener clickListener = new View.OnClickListener() {
public void OnClick(View b) {
if (buton == b) {
buton.setBackgroundColor(Color.GREEN);
}
};
}
}
出了点问题。我不明白。我想要一个按钮并单击以将其颜色更改为绿色或特定颜色代码。
如何使用按钮更改图层的背景?
答案 0 :(得分:1)
将监听器添加到按钮:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buton = (Button) findViewById(R.id.buton_verde);
buton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
buton.setBackgroundColor(Color.GREEN);
});
}
删除if
声明:
if (buton == b) {
...
答案 1 :(得分:0)
import android.app.Activity;
import android.graphics.Color;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
private Button buton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buton = (Button) findViewById(R.id.buton_verde);
buton.setOnClickListener(clickListener);
}
View.OnClickListener clickListener = new View.OnClickListener() {
public void onClick(View v) {
if (buton == v)
buton.setBackgroundColor(Color.GREEN);
}
};
}
答案 2 :(得分:0)
这是您的固定代码。这些都在评论中解释过。
import android.app.Activity;
import android.graphics.Color;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
private Button button; // Renamed to button, not buton
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Use English words, others might read your code someday
button = (Button) findViewById(R.id.buton_verde);
View.OnClickListener clickListener = new View.OnClickListener() {
@Override
public void onClick(View b) {
button.setBackgroundColor(Color.GREEN);
// You are explicitly assiging the OnClickListener for this button
// Thus, you don't need to check if b is a button
}
};
// You have created the listener, now you need to assign it to the button
button.setOnClickListener(clickListener);
}
}