我正在使用一个方法:button_click(视图视图)在editText上设置文本,我有很多按钮,每个按钮都应该在特定的editText上设置文本。
有没有办法知道哪个按钮叫做方法,以便我可以设置正确的editText文本?
这是方法的代码:
public void button_click(View view) {
// Create the dialog
final Dialog mDateTimeDialog = new Dialog(view.getContext());
// Inflate the root layout
LayoutInflater inflater = (LayoutInflater) view.getContext().getSystemService( Context.LAYOUT_INFLATER_SERVICE );
final RelativeLayout mDateTimeDialogView = (RelativeLayout) inflater.inflate(R.layout.datepick, null);
// Grab widget instance
final DateTimePicker mDateTimePicker = (DateTimePicker) mDateTimeDialogView
.findViewById(R.id.DateTimePicker);
mDateTimePicker.setDateChangedListener(this);
// Update demo edittext when the "OK" button is clicked
((Button) mDateTimeDialogView.findViewById(R.id.SetDateTime))
.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mDateTimePicker.clearFocus();
// TODO Auto-generated method stub
String result_string = mDateTimePicker.getMonth()
+ "/"
+ String.valueOf(mDateTimePicker.getDay())
+ "/"
+ String.valueOf(mDateTimePicker.getYear())
+ " "
+ String.valueOf(mDateTimePicker.getHour())
+ ":"
+ String.valueOf(mDateTimePicker.getMinute());
edit_text1.setText(result_string);
mDateTimeDialog.dismiss();
}
});
// Cancel the dialog when the "Cancel" button is clicked
((Button) mDateTimeDialogView.findViewById(R.id.CancelDialog))
.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
mDateTimeDialog.cancel();
}
});
// Reset Date and Time pickers when the "Reset" button is clicked
((Button) mDateTimeDialogView.findViewById(R.id.ResetDateTime))
.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
mDateTimePicker.reset();
}
});
// Setup TimePicker
// No title on the dialog window
mDateTimeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
// Set the dialog content view
mDateTimeDialog.setContentView(mDateTimeDialogView);
// Display the dialog
mDateTimeDialog.show();
}
答案 0 :(得分:5)
传递的View
实际上是按钮。您需要做的就是像这样切换ID:
switch (view.getId()) {
case R.id.button1:
// Do something here related to button 1
break;
case R.id.button2:
// Do something here related to button 2
break;
}
编辑:错字
答案 1 :(得分:4)
您单击的视图是onClick
的参数。如果您需要其ID,可以通过
int id = view.getId();
通过这种方式,您可以打开R.id.yourButtonId来了解哪些已被点击
答案 2 :(得分:2)
你很幸运 - 传递给你的处理程序的View view
是被点击的实际视图。所以视图本身就是按钮。查看docs。
答案 3 :(得分:0)
在这个方法中,你已经传递了被激活的事件(Button)v
应该给你参考的视图
public void onClick(View v)