在PopupWindow中添加列表在开发中还是比较常见的应用,在列表中的item底部和顶部的跳跃,在遥控设备上应用理广泛(如STB)。故有此例,备忘。
public class TestPopupWindow extends Activity {
private ListView listView;
private PopupWindow popupWindow;
private TextView textView;
private Button myButton;
private String[] name;
private int iFirstOrLastItemSelected;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myButton = (Button) findViewById(R.id.button);
//从string中获取字符数组
name = getResources().getStringArray(R.array.name_one);
//监听按钮
myButton.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View arg0) {
initPopWindow();
}
});
}
private void initPopWindow() {
//得到PopupWindow的布局
View contentView = LayoutInflater.from(getApplicationContext())
.inflate(R.layout.popupwindow, null);
contentView.setBackgroundColor(Color.DKGRAY);
//设置PopWindow的宽高
popupWindow = new PopupWindow(findViewById(R.id.mainLayout), 400, 500);
popupWindow.setContentView(contentView);
textView = (TextView) contentView.findViewById(R.id.text);
textView.setText("Test");
listView = (ListView) contentView.findViewById(R.id.list);
//向adapter装载数据
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, name);
listView.setAdapter(adapter);
if (popupWindow != null) {
popupWindow.dismiss();
}
popupWindow.setFocusable(true);
//显示PopupWindow
popupWindow.showAsDropDown(contentView);
//监听PopupWindow中的选中(高亮)的item
listView.setOnItemSelectedListener(itemSelectedListener);
//监听键盘按键
listView.setOnKeyListener(popuWindowListener);
//监听并响应所点击的item
listView.setOnItemClickListener(clickListener);
}
OnItemClickListener clickListener = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
//在此可实现响应item被点击后的功能
popupWindow.dismiss();
}
};
OnItemSelectedListener itemSelectedListener = new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
iFirstOrLastItemSelected = position;
}
public void onNothingSelected(AdapterView<?> parent) {
}
};
private OnKeyListener popuWindowListener = new OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_UP:
if (iFirstOrLastItemSelected == 0) {
listView.setSelection(name.length - 1);
}
break;
case KeyEvent.KEYCODE_DPAD_DOWN:
if (iFirstOrLastItemSelected == name.length - 1) {
listView.setSelection(0);
}
break;
}
}
return false;
}
};
}