1. 程式人生 > >android實現帶下拉列表的文字框

android實現帶下拉列表的文字框

android實現帶下拉列表的文字框

keywords:android studio、EditText、ImageView、PopupMenu。
效果

  1. 佈局
<TextView
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:layout_marginTop="5dp"
               android:text="姓名"
               android:
textSize="20sp" android:gravity="center" android:padding="20dp"/> <EditText android:id="@+id/name_text" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:
background="@null" android:height="35dp" /> <ImageView android:id="@+id/dropdown" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:layout_marginBottom=
"2dp" android:layout_marginTop="2dp" android:background="#D3D3D3" android:onClick="babyname_onClick" android:paddingRight="2dp" android:scaleType="fitXY" android:src="@drawable/dropdown"/>

2.menu定義–menu_name.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
   <item
       android:id="@+id/item01"
       android:orderInCategory="100"
       android:title="張三"/>
   <item
       android:id="@+id/item02"
       android:orderInCategory="101"
       android:title="李四"/>
</menu>

3.java程式碼

public class setinfo extends Activity {  
  public EditText  et;
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.setinfo);
      name_text=(EditText) findViewById(R.id.name_text);
      }
  public void babyname_onClick(View v) {
      PopupMenu pm=new PopupMenu(this, name_text);
      pm.getMenuInflater().inflate(R.menu.menu_name, pm.getMenu());
      pm.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
          @Override
          public boolean onMenuItemClick(MenuItem item) {
              name_text.setText(item.getTitle());
              return false;
          }
      });
      pm.show();
  }
  }