0
1

More than 5 years have passed since last update.

【Android】ListPopupWindowを使った入力候補の表示

Posted at

0.実行例

スクリーンショット 2019-03-27 19.13.33.png

1.コード全体

MainActivity.java
package com.example.listpopupwindowtest;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListPopupWindow;

public class MainActivity extends AppCompatActivity {

    String[] strList = {"あいうえお","かきくけこ","さしすせそ"};

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

        final EditText et_1 = (EditText)findViewById(R.id.et_1);
        final ListPopupWindow lpw = new ListPopupWindow(this);
        lpw.setAdapter(new ArrayAdapter<String>(
                this,android.R.layout.simple_list_item_1,strList));
        lpw.setAnchorView(et_1);
        lpw.setModal(true);
        et_1.setOnTouchListener(new View.OnTouchListener() {
            final int DRAWABLE_RIGHT = 2;
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(event.getAction()==MotionEvent.ACTION_UP){
                    if(event.getX()>=v.getWidth()-((EditText) v)
                            .getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width()){
                        lpw.show();
                        ((InputMethodManager)getSystemService(INPUT_METHOD_SERVICE))
                                .hideSoftInputFromWindow(v.getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
                        return true;
                    }
                }
                return false;
            }
        });
        lpw.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                et_1.setText(strList[position]);
                lpw.dismiss();
            }
        });
    }
}

2.入力欄の右端に▼マークを付ける

下記のリソースファイルをダウンロードし、core/res/res/drawable-hdpi/numberpicker_down_normal_holo_light.pngをdrawableフォルダにコピーする。
https://android.googlesource.com/platform/frameworks/base/+/efd1c67

EditTextのdrawableRightで、コピーした画像ファイルを指定する。


    <EditText
        android:id="@+id/et_1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:drawableRight="@drawable/numberpicker_down_normal_holo_light"/>

参考

EditText with a Popup List

0
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1