PopupWindow里显示listview 解决ListView取不到ItemClick事件问题

PopupWindow里显示listview 解决ListView取不到ItemClick事件问题


package com.example.popupwindow;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.PopupWindow;

public class MainActivity extends Activity {
	Button button1;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button1=(Button)findViewById(R.id.button1);
        
        button1.setOnClickListener(new OnClickListener(){

			public void onClick(View v) {
				// TODO Auto-generated method stub
				//生成ListView
				ListView listview=new ListView(MainActivity.this);
				String[] strs=new String[3];
				strs[0]="asfsafdasdf";
				strs[1]="桂 地要仍地沃尔夫仍";
				strs[2]="asfsafdasdf";
				ArrayAdapter adapter=new ArrayAdapter(MainActivity.this,R.layout.item,R.id.text1,strs);
				listview.setAdapter(adapter);
				listview.setOnItemClickListener(new OnItemClickListener() {

					public void onItemClick(AdapterView parent, View view, int position, long id) {
						// TODO Auto-generated method stub
						System.out.println(position);
					}
				});
				
				PopupWindow window=new PopupWindow(MainActivity.this);
				//设置宽高
				window.setWidth(200);
				window.setHeight(120);
				//填充
				window.setContentView(listview);
				//外部可部
				window.setOutsideTouchable(true);
				//加了下面这行,onItemClick才好用
				window.setFocusable(true);
				window.showAsDropDown(button1);

			}});
        
    }

}

© 2012, 冰冻鱼. 请尊重作者劳动成果,复制转载保留本站链接! 应用开发笔记