Android 에서 EditText 의 drawableRight 속성 설정 클릭 이벤트

이 방법 은 EditText 뿐만 아니 라 TextView,AutoComplete TextView 등 컨트롤 에 도 적용 된다.
Google 공식 API 는 오른쪽 그림 의 클릭 이 벤트 를 설정 하 는 직접적인 방법 을 제시 하지 않 았 습 니 다.따라서 클릭 위 치 를 통 해 클릭 이 벤트 를 판단 해 야 합 니 다.

레이아웃 파일:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:paddingBottom="@dimen/activity_vertical_margin"
  android:paddingLeft="@dimen/activity_horizontal_margin"
  android:paddingRight="@dimen/activity_horizontal_margin"
  android:paddingTop="@dimen/activity_vertical_margin"
  tools:context="com.example.drablerighttest.MainActivity" >

  <EditText
    android:id="@+id/et"
    android:layout_width="350dp"
    android:layout_height="wrap_content"
    android:drawableRight="@drawable/search_clear_pressed"
    android:text="@string/hello_world" />

</RelativeLayout>
MainActivity.java

public class MainActivity extends Activity {

  private EditText et;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    et = (EditText) this.findViewById(R.id.et);
    et.setOnTouchListener(new OnTouchListener() {

      @Override
      public boolean onTouch(View v, MotionEvent event) {
        // et.getCompoundDrawables()       4   ,            
        Drawable drawable = et.getCompoundDrawables()[2];
        //        ,    
        if (drawable == null)
          return false;
        //        ,    
        if (event.getAction() != MotionEvent.ACTION_UP)
          return false;
        if (event.getX() > et.getWidth()
            - et.getPaddingRight()
            - drawable.getIntrinsicWidth()){
          et.setText("");
        }
          return false;
      }
    });
  }
}
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기