首页 > Windows开发 > 详细

巧用PopupWindow

时间:2015-11-05 16:57:07      阅读:228      评论:0      收藏:0      [点我收藏+]

PopupWindow是一种简便的弹出界面,常用的场合是点击按钮之后,会在按钮下方弹出一个界面,界面是自定义的,与一般的对话框不同,PopupWindow弹出的初始位置默认是在显示PopupWindow控件的下方。

以下是我自定义的一个PopupWindow,好处就是把PopupWindow相关的代码都集中到一个类里面,方便复用

public class MyPopupWindow {
	private Context mContext;
	private PopupWindow mPopupWindow;
	private View rootView;
	public TextView test;

	public   MyPopupWindow(Context context) {
		mContext = context;
		rootView = LayoutInflater.from(mContext).inflate(
				R.layout.popup_window_layout, null);
	        // 初始化
		mPopupWindow=new PopupWindow(rootView,LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		//设置动画样式
		mPopupWindow.setAnimationStyle(R.style.AnimationPreview);
		//设置点击空白处会消失
		mPopupWindow.setTouchable(true);
        mPopupWindow.setOutsideTouchable(true);
        mPopupWindow.setBackgroundDrawable(new BitmapDrawable(mContext.getResources(), (Bitmap) null));
        initViews();
	}

	private void initViews() {
		// TODO Auto-generated method stub
		test=(TextView) rootView.findViewById(R.id.tv_pop);
	}
        //显示PopupWindow
	public void show(View v) {
		// TODO Auto-generated method stub
		//可以设置偏移量mPopupWindow.showAsDropDown(v, xoff, yoff);
		 mPopupWindow.showAsDropDown(v);
		 
	}
	//关闭PopupWindow
	public void close(){
		mPopupWindow.dismiss();
	}
}

PopupWindow布局文件,简单起见只添加一个TextView

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/tv_pop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
       
        />
</LinearLayout>

使用:

public class MainActivity extends Activity implements OnClickListener{

private MyPopupWindow myPopupWindow;
private Button btn;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		btn = (Button)findViewById(R.id.btn);
		btn.setOnClickListener(this);
		//初始化我的PopupWindow
		myPopupWindow = new MyPopupWindow(mContext);
	}
    
    @Override
	public void onClick(View v) {
		if (v == btn) {
		myPopupWindow.test.setText("测试PopupWindow");
			myPopupWindow.show(v);
		}
	}
}


巧用PopupWindow

原文:http://my.oschina.net/carbenson/blog/526563

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!