如下例子:当点击Button控件时,会弹出两个button控件(也可以是其它控件)
这是.xml文件:
<RelativeLayout
android:id="@+id/top"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:background="@drawable/title_bg_blue"
>
<TextView
android:textSize="@dimen/text_size"
android:textColor="@color/black"
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:text="好友分类" />
<Button
android:background="@drawable/button_selector"
android:id="@+id/btn_group_list_more"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:text="更多" />
</RelativeLayout>
当点击更多的Button时,会在其下方显示.xml的View
关键代码:
btnMore = (Button) view.findViewById(R.id.btn_group_list_more);
top = (RelativeLayout) view.findViewById(R.id.top);
/**
* 监听更多按钮,当点击更多时,会显示收藏和频道历史记录
*/
btnMore.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(viewMore==null){
//获取.xml的view
viewMore = View.inflate(TvStationActivity.this, R.layout.more, null);
btnHistory = (Button)viewMore.findViewById(R.id.btn_more_history);
btnSave = (Button)viewMore.findViewById(R.id.btn_more_channel);
}
if(popupWindow==null){
//初始化窗口,绑定viewMore
popupWindow = new PopupWindow(viewMore,// 设置要显示的view并设置其显示的宽和高
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
}
if(!isClose){
//显示设置其显示的位置:相对layoutTop放置在右顶点,
popupWindow.showAtLocation(layoutTop, Gravity.TOP|Gravity.RIGHT, 0, layoutTop.getHeight()+btnMore.getHeight()+38);
isClose = true;
Log.i("infp", "==open");
}else{
closePopupWindow();
}
}
});
boolean isclose = false;
//关闭弹出的view窗口
/**
* 关闭弹出的窗口
*/
public void closePopupWindow() {
if (this.popupWindow != null && popupWindow.isShowing()) {
popupWindow.dismiss();
popupWindow = null;
isclose = false;
}
}