下面这个例子是回顾一下PopupWindow的用法,最近工作不太忙,想把以前的都复写一下。以方便自己的记忆。都是最基本的用法。
这个例子就是讲解PopupWindow的用法,通过点击一个button,显示popupWindow的内容。
效果图:
点击按钮之后的效果:
下面就看源代码:
主程序MainActivity.java
package com.example.testpopupwindow;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.PopupWindow;
public class MainActivity extends Activity {
private Button showPopButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showPopButton = (Button) findViewById(R.id.popButton);
View rootView = getLayoutInflater().inflate(R.layout.popupwindow_main,
null);
final PopupWindow popupWindow = new PopupWindow(rootView, 280, 360);
showPopButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 以下拉的方式显示
popupWindow.showAsDropDown(v);
//将PopupWindow显示在固定位置
//popupWindow.showAtLocation(findViewById(R.id.popButton), Gravity.CENTER, 40, 0);
});
rootView.findViewById(R.id.close).setOnClickListener(
new OnClickListener() {
@Override
public void onClick(View v) {
popupWindow.dismiss();
}
});
}
}
主布局文件:activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<Button
android:id="@+id/popButton"
android:layout_width="280dp"
android:layout_height="wrap_content"
android:text="show popupWindow" />
</RelativeLayout><span style="color:#ff0000;">
</span>
popupWindow.xml文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="button1" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="button2" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="button3" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="button4" />
<Button
android:id="@+id/close"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="关闭" />
</LinearLayout>
下载源码请点击: 源码下载