带弹出列表的EditText

布局文件如下


  • 显示效果


    带弹出列表的EditText_第1张图片
  • 点击事件

 关于点击事件,就是设置EditText的OnTouchListener,在点击到右边的图标的范围时做相应的操作
etTest.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        final int DRAWABLE_LEFT = 0;
        final int DRAWABLE_TOP = 1;
        final int DRAWABLE_RIGHT = 2;
        final int DRAWABLE_BOTTOM = 3;

        // Check if touch point is in the area of the right button
        if(event.getAction() == MotionEvent.ACTION_UP) {
            if(event.getX() >= (etTest.getWidth() - etTest
                .getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) {
                // your action here
                return true;
            }
        }
        return false;
    }
});
  • 显示列表
 使用[ListPopupWindow]
  • 代码如下
import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListPopupWindow;

public class MainActivity extends Activity implements OnTouchListener,
        OnItemClickListener {

    private EditText etTest;
    private ListPopupWindow lpw;
    private String[] list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        etTest = (EditText) findViewById(R.id.et_test);
        etTest.setOnTouchListener(this);

        list = new String[] { "item1", "item2", "item3", "item4" };
        lpw = new ListPopupWindow(this);
        lpw.setAdapter(new ArrayAdapter(this,
                android.R.layout.simple_list_item_1, list));
        lpw.setAnchorView(etTest);
        lpw.setModal(true);
        lpw.setOnItemClickListener(this);
    }

    @Override
    public void onItemClick(AdapterView parent, View view, int position, long id) {
        String item = list[position];
        etTest.setText(item);
        lpw.dismiss();
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        final int DRAWABLE_RIGHT = 2;

        if (event.getAction() == MotionEvent.ACTION_UP) {
            if (event.getX() >= (v.getWidth() - ((EditText) v)
                    .getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) {
                lpw.show();
                return true;
            }
        }
        return false;
    }
}

你可能感兴趣的:(带弹出列表的EditText)