ClickListener当前目标

时间:2011-02-05 00:55:28

标签: android event-handling listener

EditText etHomePhone = (EditText)findViewById(R.id.et_pi_home_phone);
EditText etMobilePhone = (EditText)findViewById(R.id.et_pi_home_phone);

etHomePhone.setOnClickListener(showPopUpClickListener);
etMobilePhone.setOnClickListener(showPopUpClickListener);


    private View.OnClickListener showPopUpClickListener = new View.OnClickListener() {

            public void onClick(View v) {

              /* I like to get both EditText.getText().toString() value in this one ClickListener 
 is it Possible, there is something in ActionScript call event.currentTarget...
*/  

            }
        };

2 个答案:

答案 0 :(得分:0)

如果您将etHomePhone和etMobilePhone变量声明为final并在同一方法中内联定义OnClickListener,则可以直接引用这些变量。像这样:

final EditText etHomePhone = (EditText)findViewById(R.id.et_pi_home_phone);
final EditText etMobilePhone = (EditText)findViewById(R.id.et_pi_home_phone);

View.OnClickListener showPopUpClickListener = new View.OnClickListener() {

    public void onClick(View v) {
        String home = etHomePhone.getText().toString();
        String mobile = etMobilePhone.getText().toString();
        // Do something with home and mobile
    }
};

etHomePhone.setOnClickListener(showPopUpClickListener);
etMobilePhone.setOnClickListener(showPopUpClickListener);

编辑:

如果您只想获取被点击的EditText而不是两者的文本,那么您可以通过onClick(View v)投射它传递的视图:

public void onClick(View v) {
    EditText editText = (EditText)v;
    String phoneNumber = editText.getText().toString();
    // Do something with phoneNumber
}

答案 1 :(得分:0)

这是一个片段,因此我看不到上下文,但您可以构建一个OnClickListener来捕获活动中的所有事件。首先,您的活动需要实现OnClickListener接口:

public class YourActivity extends Activity implements OnClickListener {...

在OnCreate()方法中,注册每个应响应点击的UI元素,如下所示:

yourObject.setOnClickListener(this);

接下来,对于activity的onClick()方法,使用R.id创建一个开关结构,如下所示:

@Override
public void onClick(View view) {
   switch(view.getId()){
   case R.id.A_UI_Element:
      //do what you need for this element
      break:
   case R.id.A_Different_UI_Element:
      //do what you need for this element
      break;
   //continue with cases for each element you want to be clickable
   }
}

不要忘记每个案件结束时的休息时间。

我在您的代码中注意到的一件事:editText声明都引用相同的资源。这为您提供了两个相同UI元素的句柄,而不是两个不同的元素。