package com.example.popupwindowdemo01;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener {
private Button main_button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 注释原本的布局
// setContentView(R.layout.activity_main);
// 实例化布局
LinearLayout llayout = new LinearLayout(this);
// 设置布局方向
llayout.setOrientation(LinearLayout.VERTICAL);
// 添加到activity中
this.setContentView(llayout);
// 实例化按钮
main_button = new Button(this);
// 设置按钮的文字
main_button.setText("show popu");
// 把按钮添加到布局中
llayout.addView(main_button);
// 为按钮添加点击事件
main_button.setOnClickListener(this);
}
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
// 实例化一个textview
TextView v = new TextView(this);
// 注意:一定要让这个view有高宽,也可以设置文字让view被动设置高宽
// 也可手动写v.setHeight(50);v.setWidth(50);
v.setText("i am is a button");
v.setBackgroundColor(Color.GREEN);
// 实例化PopupWindow
// 这里面的第一个参数是一个View,只要是view并且有高宽即可
// 二,三个参数是PopupWindow的高宽,不是第一个参数View的高宽
PopupWindow pp = new PopupWindow(v,
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
// 出现在按钮的下面,可设其他位置
pp.showAsDropDown(main_button);
}
}
运行截图: