我有一些ImageButton,当我按下按钮一个字母必须在我的EditText中显示。 如果它与我给出的字母不匹配,那么我的图像会振动。 请帮帮我,我是android新手。 这是我的代码 package com.example.image;
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ImageButton button1;
final ImageButton button2;
final ImageButton button3;
final EditText input;
Button chk;
chk =(Button) findViewById(R.id.button1);
button1 =(ImageButton) findViewById(R.id.imageButton1);
button2 =(ImageButton) findViewById(R.id.imageButton2);
button3 =(ImageButton) findViewById(R.id.imageButton3);
input =(EditText) findViewById(R.id.editText1);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
input.setText("a");
}
});
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
input.setText("B");
}
});
button3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
;
input.setText("C");
}
});
chk.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String check = input.getText().toString();
if(check.contentEquals("ABC")){
Vibrator vib = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 100ms
vib.vibrate(300);
}
else{
input.setText("");
Vibrator vib = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 100ms
vib.vibrate(300);
}
}
});
}
}
答案 0 :(得分:1)
也许这就是答案:
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
input.setText(input.getText() + "A");
}
});
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
input.setText(input.getText() + "B");
}
});
button3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
;
input.setText(input.getText() + "C");
}
});
答案 1 :(得分:0)
创建如下方法
private void updateText(String char){
String inputText = input.getText().toString() + char;
input.setText(inputText);
}
然后从所有按钮(button1,button2,button3)中调用此方法clickListener like
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
updateText("A");
}
});