实例,当点击button时,在他的旁边显示其他的窗口
一,layout 布局文件
这个是MainActivity 的布局文件 activity_main.xml
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<Button
android:id="@+id/button_more"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Button" />
</RelativeLayout>
popupWindow 的布局文件 more.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/button_add_friend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
二, 在MainActivity 中的代码
public class MainActivity extends Activity {
PopupWindow popupWindow;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化控件
final Button btnMore = (Button) findViewById(R.id.button_more);
// 给button添加监听器
btnMore.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//popupWindow等于null 才创建,只能创建一次
//不等于null 说明已经显示了 就不会再创建了
if (popupWindow==null)
{
// 显示more.xml
// 先加载more.xml 这个布局文件
View view = View.inflate(MainActivity.this, R.layout.more,null);
popupWindow = new PopupWindow(view,
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
Log.i("popupWindow", "new " + popupWindow.toString());
int btnMoreHeight = btnMore.getHeight();
// 只有先测量 才能得到控件的高度
view.measure(0, 0);
int viewHeight = view.getMeasuredHeight();
int y = btnMoreHeight + viewHeight;
// 显示在相对btnMore的位置 这个位置的 x y
popupWindow.showAsDropDown(btnMore, 0, -y);
Button btnAddFriend = (Button) view.findViewById(R.id.button_add_friend);
//给这个控件添加监听器,点击控件让这个弹出窗口消失
btnAddFriend.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Log.i("popupWindow","close " + popupWindow.toString());
popupWindow.dismiss();
popupWindow = null;
}
});
}
}
});
}
}