我是Android和java编程的初学者,所以我无法理解为什么我的switch语句不适用于按钮元素。
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
Button button1;
Button button2;
Button button3;
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button3 = (Button) findViewById(R.id.button3);
textView = (TextView) findViewById(R.id.textView);
View.OnClickListener onClickListener = new View.OnClickListener() {
@Override
这是我的问题
public void onClick(View v) {
switch(v.getId()){
case R.id.button1:
textView.setText("Button1 was pressed");
break;
case R.id.button2:
textView.setText("Button2 was pressed");
break;
case R.id.button3:
textView.setText("Button3 was pressed");
break;
}
}
};
}
}
如果有人帮助我,我会非常感激。
P.S。 我是编程初学者
答案 0 :(得分:1)
您尚未在setOnClickListner
上写Button
并确保Activity
implements View.OnClickListener
在下方查看我的代码。
button1.setOnClickListener(this);
button2.setOnClickListener(this);
button3.setOnClickListener(this);
使用此代码。
public class MainActivity extends AppCompactActivity implements View.OnClickListener {
Button button1;
Button button2;
Button button3;
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button3 = (Button) findViewById(R.id.button3);
textView = (TextView)findViewById(R.id.textview) ;
button1.setOnClickListener(this);
button2.setOnClickListener(this);
button3.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.button1:
textView.setText("Button1 was pressed");
break;
case R.id.button2:
textView.setText("Button2 was pressed");
break;
case R.id.button3:
textView.setText("Button3 was pressed");
break;
}
}
}