美文网首页
popupwindow简单使用(一)

popupwindow简单使用(一)

作者: 落叶随风花落入泥 | 来源:发表于2017-11-15 13:58 被阅读0次

根据网上的popupwind总结,整理一份自己实践过的知识,进行备用

1 概述

自己理解的是他就是以弹出对话框,与AlertDialog的作用类似,popupwindow 
更灵活,其位置可以根据你自己的需求随意设置,而AlertDialog默认是显示在布
局的中间,灵活性而言popupwind更优。

2 popupwind函数

1)构造函数有四个
public PopupWindow (Context context)          
public PopupWindow(View contentView)             
public PopupWindow(View contentView, int width, int height)              
public PopupWindow(View contentView, int width, int height, boolean 
focusable) 
3 popupwindow使用注意点

必须设置三个条件,①contentView ②width ③hight ,有这三个条件才能弹出。
所以popupwindow的构造函数三个参数的是我们开发首选。

4 popupwindow显示函数
主要使用三个:
//相对某个控件的位置(正左下方),无偏移  
① showAsDropDown(View anchor):  
//相对某个控件的位置,有偏移;xoff表示x轴的偏移,正值表示向左,负值表示向
右;yoff表示相对y轴的偏移,正值是向下,负值是向上;  
② showAsDropDown(View anchor, int xoff, int yoff):  
//相对于父控件的位置(例如下方Gravity.BOTTOM ),可以设置偏移或无偏移 
③ showAtLocation(View parent, int gravity, int x, int y):

5 实践Demo
需求就是,布局结构是 viewpager + textView,点击textview就从布局的底部弹
出一个popupwindow,popupwindow里面是一个listview

①适配器代码如下:
public class mmAdapter extends BaseAdapter {

    @Override
    public int getCount() {
        return listItems.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) 
{

        MyPopupwindowViewHolder mpv;

        if (convertView == null) {

            convertView = View.inflate(MainActivity.this, 
R.layout.popupwindow_item, null);
            mpv = new MyPopupwindowViewHolder();
            mpv.test = (TextView) 
convertView.findViewById(R.id.tv_popuowindows);

            convertView.setTag(mpv);

        } else {
            mpv = (MyPopupwindowViewHolder) convertView.getTag();
        }

        mpv.test.setText(listItems.get(position));
        mpv.test.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Toast.makeText(MainActivity.this, "popupwindows里面
的"+position+"条目被点击了", Toast.LENGTH_SHORT).show();
                popupWindow.dismiss();
            }
        });
        return convertView;
    }
}
public class MyPopupwindowViewHolder {
    TextView test;
}

② TextView的点击事件的代码
//popupwind 自己的布局
View view = View.inflate(this, R.layout.popupwindowview, null);
popupWindow = new PopupWindow(view, 
ViewGroup.LayoutParams.MATCH_PARENT, 
ViewGroup.LayoutParams.MATCH_PARENT);
popupWindow.setContentView(view);
listView = (ListView) view.findViewById(R.id.lv_listView);
listView.setAdapter(new mmAdapter());

//这是获取父布局,让其从父布局的下方显示
View mainView = 
LayoutInflater.from(MainActivity.this).inflate(R.layout.activity_main, null);
popupWindow.showAtLocation(mainView, Gravity.BOTTOM, 0, 0);

相关文章

网友评论

      本文标题:popupwindow简单使用(一)

      本文链接:https://www.haomeiwen.com/subject/arwcvxtx.html