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();
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
来源:http://www.informit.com/articles/article.aspx?p=2078060&seqNum=4