我是Android开发的新手,所以这是我的问题。
我有一系列按钮,我想显示Toast
说"此按钮将启动" 按下按钮的getText值。
修改
按钮数组的声明和初始化代码。
final Button buttons[] = new Button[6];
buttons[0] = (Button) findViewById(R.id.button1);
buttons[1] = (Button) findViewById(R.id.button2);
buttons[2] = (Button) findViewById(R.id.button3);
buttons[3] = (Button) findViewById(R.id.button4);
buttons[4] = (Button) findViewById(R.id.button5);
buttons[5] = (Button) findViewById(R.id.button6);
所以,
for(i = 0; i< buttons.length; i++){
buttons[i].setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
Log.d("test","Why is this not appearing in logcat");
CharSequence buttonvalue = buttons[i].getText();
Context context = getApplicationContext();
System.out.println(buttonvalue);
CharSequence text = "This button will launch" + buttonvalue + " App!!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
});
}
当我按下按钮时,应用程序编译得很好但崩溃了。我似乎无法调试它因为System.out.println()
和Logcat都没有出现或我只是看错了地点。那么我应该在哪里找到这些消息呢?
答案 0 :(得分:3)
尝试按照我的示例,在没有LogCat的情况下实施起来更简单:
private static final int[] idArray = {R.id.button0, R.id.button1, R.id.button2, R.id.button3, R.id.button4, R.id.button5};
private Button[] bt = new Button[idArray.length];
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start_layout);
for (int i=0; i<idArray.length; i++) {
final int b = i;
bt [b] = (Button)findViewById(idArray[b]); // Fetch the view id from array
bt [b].setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"This button will launch" + bt[b].getText().toString() + " App!!";,Toast.LENGTH_LONG).show(); }
});
}
}