PopupWindow是android中使用者比較喜歡的一個控制項,運用起來也比較簡單,新浪微部落格戶端中就用到PopupWindow來選擇好友分類。
今天我們做的就是它了,popupWindow裡放一個ListView。
首先我們看到popupWindow裡是一個listView,我們用布局實現這個ListView:
<?xml version="1.0"encoding="UTF-8"?><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android" android:id = "@+id/popupLayout" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:background="#aa000000"> <ListView android:id="@+id/customer_popuplist" android:layout_width="fill_parent" android:layout_height="fill_parent"/></LinearLayout>
然後我們就將他執行個體化並添加到PopupWindow裡:
button =(Button)findViewById(R.id.button); button.setOnClickListener(newView.OnClickListener() { @Override publicvoid onClick(View v) { //TODO Auto-generated method stub showPopup(); } }); } private void showPopup(){ //listview的顯示條目內容 friends= new String[]{"全部","我的微博","周邊","未命名","未命名非公有","hhv"}; //得到popupWindow的顯示布局 Viewview =LayoutInflater.from(PopupWindowTestActivity.this).inflate(R.layout.popup,null); LinearLayout popuplayout =(LinearLayout)view.findViewById(R.id.popupLayout); //執行個體化listview並設定適配器 ListView list =(ListView)view.findViewById(R.id.customer_popuplist); list.setAdapter(newArrayAdapter<String>(PopupWindowTestActivity.this,android.R.layout.simple_list_item_1,friends)); //執行個體化並設定popup屬性 popup = newPopupWindow(popuplayout,180,220);//popup的布局及長寬 //強行獲得popupWindow裡面的內容的焦點(ListView),如果設為false,listView將得不到焦點,點擊listview也沒有反應 popup.setFocusable(true); //PopupWindow顯示在button下面 popup.showAsDropDown(button,70,0);//第二個參數是離button左邊100px,0是離button底部0px list.setOnItemClickListener(newOnItemClickListener() { @Override publicvoid onItemClick(AdapterView<?> parent, View v, intposition, long id) { button.setText(friends[position]); popup.dismiss(); popup= null; } }); }
好了 讓我們看一下
popupWindow的基本實現就這樣了,若要做的更美觀,就得在布局上下些功夫了! ! 呵呵,就說到這裡吧,再見!!