整体项目结构如图所示:
MainActivity.java代码下:
package com.hoperun.ray.activity;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.PopupWindow;
public class MainActivity extends Activity {
private Button btn;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//调用弹框函数
showPopupWindow(MainActivity.this, MainActivity.this.findViewById(R.id.btn));
}
});
}
/**
* 弹框方法
* @param context
* @param parent
*/
public void showPopupWindow(Context context , View parent){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//设置弹框布局
final View vPopupWindow = inflater.inflate(R.layout.tb, null, false);
final PopupWindow popupWindow = new PopupWindow(vPopupWindow, 300, 300, true);
popupWindow.showAtLocation(parent,Gravity.CENTER,0,0);
}
}
关闭框口调用PopupWindow.dismiss();
使用到的布局代码:
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Button
android:id="@+id/btn"
android:text="弹框"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
弹框布局tb.xml
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TableRow>
<TextView
android:text="单价"
android:padding="5dip"/>
<TextView
android:text="个数"
android:padding="3dip"/>
<TextView
android:text="总额"
android:padding="5dip"/>
</TableRow>
<TableRow>
<TextView android:id="@+id/priceTextView" android:layout_width="5dip"
android:layout_height="wrap_content" />
<TextView android:id="@+id/countTextView" android:layout_width="3dip"
android:layout_height="wrap_content" />
<TextView android:id="@+id/allpriceTextView" android:layout_width="5dip"
android:layout_height="wrap_content" />
</TableRow>
<View
android:layout_height="2dip"
android:background="#F00" />
<TableRow>
<TextView
android:text="请选择支付方式:"
android:layout_span="3"
android:background="#FFC0C0C0"
android:textColor="#f00"
android:layout_width="fill_parent"/>
</TableRow>
<TableRow>
<ImageView/>
<TextView
android:text="手机支付"
android:layout_span="2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</TableRow>
<TableRow>
<ImageView/>
<TextView
android:text="信用卡支付"
android:layout_span="2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</TableRow>
</TableLayout>
效果如下图: