ANDROID笔记:ListPopupWindow的使用
You can use ListPopupWindow to anchor to a host view and display a list of options. In this recipe, you will learn to anchor ListPopupWindow to an EditTextcontrol. When the user clicks in theEditText control, ListPopupWindow will appear displaying a list of options. After the user selects an option from ListPopupWindow, it will be assigned to the EditText control. Create a new Android project called ListPopupWindowApp.
ListPopupWindowAppActivity.java package com.androidtablet.listpopupwindowapp; import android.os.Bundle; import android.app.Activity; import android.widget.ListPopupWindow; import android.view.View; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView; import android.view.View.OnClickListener; public class ListPopupWindowAppActivity extends Activity implements OnItemClickListener { EditText productName; ListPopupWindow listPopupWindow; String[] products={"Camera", "Laptop", "Watch","Smartphone", "Television"}; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_list_popup_window_app); productName = (EditText) findViewById( R.id.product_name); listPopupWindow = new ListPopupWindow( ListPopupWindowAppActivity.this); listPopupWindow.setAdapter(new ArrayAdapter( ListPopupWindowAppActivity.this, R.layout.list_item, products)); listPopupWindow.setAnchorView(productName); listPopupWindow.setWidth(300); listPopupWindow.setHeight(400); listPopupWindow.setModal(true); listPopupWindow.setOnItemClickListener( ListPopupWindowAppActivity.this); productName.setOnClickListener(new OnClickListener() { public void onClick(View v) { listPopupWindow.show(); } }); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { productName.setText(products[position]); listPopupWindow.dismiss(); } }
list_item.xml <?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="6dp" android:textSize="@dimen/text_size" android:textStyle="bold" />
activity_list_popup_window_app.xml <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/product_name" android:hint="Enter product name" android:textSize="@dimen/text_size" /> </LinearLayout>
转自:http://www.informit.com/articles/article.aspx?p=2078060&seqNum=4
书籍:The Android Developer's Cookbook