Android之ListPopupWindow

2015-01-29 11:58:00
zengde
来源:
http://blog.csdn.net/jsnrwzm/article/details/14408835
转贴 572

Android的弹出列表对话框实现十分丰富,但是大部分不易于定制,除非是自己重写。但是ListPopupWindow是api11之后新添加的widget组件,十分有利于列表对话框的定制。下面就以一个简单的例子作以说明。

 

1、两个布局文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/txt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
	
</LinearLayout>

 

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/btn"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />  //自定义的列表子项,方便展示

2、对应的Java代码

package org.zqy.android_1106_2;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListPopupWindow;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

	private TextView txt;
	private ListPopupWindow lpw;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		txt = (TextView) findViewById(R.id.txt);
		txt.setOnLongClickListener(new OnLongClickListener() {
			@Override
			public boolean onLongClick(View v) {
				lpw = new ListPopupWindow(MainActivity.this);
				final String[] strs = { "编辑", "清空" };
				lpw.setOnItemClickListener(new OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {
						Toast.makeText(MainActivity.this, strs[position],
								Toast.LENGTH_SHORT).show();
					}
				});

				lpw.setAdapter(new ArrayAdapter<String>(MainActivity.this,
						R.layout.test, strs));
				View anchor = v;
				if (anchor != null) {
					lpw.setAnchorView(anchor);// 设置ListPopupWindow漂浮于anchor上,不写会导致空指针
				}
				lpw.setWidth(100);
				lpw.show();
				return false;
			}
		});

	}

}

 

ListPopupWindow可以监听setOnDismissListener来监听其展现状态。

 

3、运行结果

 

博客分类