GVKun编程网logo

Android自定义PopupWindow仿点击弹出分享功能(android自定义弹窗点击事件)

13

对于Android自定义PopupWindow仿点击弹出分享功能感兴趣的读者,本文将提供您所需要的所有信息,我们将详细讲解android自定义弹窗点击事件,并且为您提供关于androidPopupWi

对于Android自定义PopupWindow仿点击弹出分享功能感兴趣的读者,本文将提供您所需要的所有信息,我们将详细讲解android自定义弹窗点击事件,并且为您提供关于android PopupWindow、Android PopupWindow 实现自定义菜单弹窗效果、Android Popupwindow 拖动、Android PopupWindow实现右侧、左侧和底部弹出菜单的宝贵知识。

本文目录一览:

Android自定义PopupWindow仿点击弹出分享功能(android自定义弹窗点击事件)

Android自定义PopupWindow仿点击弹出分享功能(android自定义弹窗点击事件)

本文实例自定义PopupWindow,点击弹出PopupWindow,背景变暗,仿点击弹出分享功能,供大家参考,具体内容如下

注:参照大神代码写的

自定义代码

package com.duanlian.popupwindowdemo; 
 
import android.app.Activity; 
import android.content.Context; 
import android.graphics.drawable.ColorDrawable; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.WindowManager; 
import android.widget.LinearLayout; 
import android.widget.PopupWindow; 
import android.widget.TextView; 
 
/** 
 * 自定义popupWindow 
 */ 
 
public class RewritePopwindow extends PopupWindow { 
  private View mView; 
 
  public RewritePopwindow(Activity context,View.OnClickListener itemsOnClick) { 
    super(context); 
    initView(context,itemsOnClick); 
  } 
 
  private void initView(final Activity context,View.OnClickListener itemsOnClick) { 
    LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    mView = mInflater.inflate(R.layout.popupwindow_share,null); 
    LinearLayout weiXFriend = (LinearLayout) mView.findViewById(R.id.weixinghaoyou); 
    LinearLayout friendster = (LinearLayout) mView.findViewById(R.id.pengyouquan); 
    LinearLayout QQFriend = (LinearLayout) mView.findViewById(R.id.qqhaoyou); 
    LinearLayout QQZone = (LinearLayout) mView.findViewById(R.id.qqkongjian); 
    TextView canaleTv = (TextView) mView.findViewById(R.id.share_cancle); 
    canaleTv.setonClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
 
        //销毁弹出框 
        dismiss(); 
        backgroundAlpha(context,1f); 
      } 
    }); 
    //设置按钮监听 
    weiXFriend.setonClickListener(itemsOnClick); 
    friendster.setonClickListener(itemsOnClick); 
    QQFriend.setonClickListener(itemsOnClick); 
    QQZone.setonClickListener(itemsOnClick); 
    //设置SelectPicPopupWindow的View 
    this.setContentView(mView); 
    //设置SelectPicPopupWindow弹出窗体的宽 
    this.setWidth(WindowManager.LayoutParams.FILL_PARENT); 
    //设置SelectPicPopupWindow弹出窗体的高 
    this.setHeight(WindowManager.LayoutParams.WRAP_CONTENT); 
    //设置SelectPicPopupWindow弹出窗体可点击 
    this.setFocusable(true); 
    //设置PopupWindow可触摸 
    this.setTouchable(true); 
    //设置非PopupWindow区域是否可触摸 
//    this.setoutsidetouchable(false); 
    //设置SelectPicPopupWindow弹出窗体动画效果 
//    this.setAnimationStyle(R.style.select_anim); 
    //实例化一个ColorDrawable颜色为半透明 
    ColorDrawable dw = new ColorDrawable(0x00000000); 
    //设置SelectPicPopupWindow弹出窗体的背景 
    this.setBackgroundDrawable(dw); 
    backgroundAlpha(context,0.5f);//0.0-1.0 
    this.setondismissListener(new OndismissListener() { 
 
      @Override 
      public void ondismiss() { 
        // Todo Auto-generated method stub 
        backgroundAlpha(context,1f); 
      } 
    }); 
  } 
 
 
  /** 
   * 设置添加屏幕的背景透明度 
   * 
   * @param bgalpha 
   */ 
  public void backgroundAlpha(Activity context,float bgalpha) { 
    WindowManager.LayoutParams lp = context.getwindow().getAttributes(); 
    lp.alpha = bgalpha; 
    context.getwindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); 
    context.getwindow().setAttributes(lp); 
  } 
 
} 

MainActivity中用

package com.duanlian.popupwindowdemo; 
 
import android.os.Bundle; 
import android.support.v7.app.AppCompatActivity; 
import android.view.Gravity; 
import android.view.View; 
import android.widget.Toast; 
 
public class MainActivity extends AppCompatActivity { 
  private RewritePopwindow mPopwindow; 
 
  @Override 
  protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    findViewById(R.id.share).setonClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
        mPopwindow = new RewritePopwindow(MainActivity.this,itemsOnClick); 
        mPopwindow.showAtLocation(view,Gravity.BottOM | Gravity.CENTER_HORIZONTAL,0); 
      } 
    }); 
  } 
 
  //为弹出窗口实现监听类 
  private View.OnClickListener itemsOnClick = new View.OnClickListener() { 
 
    public void onClick(View v) { 
      mPopwindow.dismiss(); 
      mPopwindow.backgroundAlpha(MainActivity.this,1f); 
      switch (v.getId()) { 
        case R.id.weixinghaoyou: 
          Toast.makeText(MainActivity.this,"微信好友",Toast.LENGTH_SHORT).show(); 
          break; 
        case R.id.pengyouquan: 
          Toast.makeText(MainActivity.this,"朋友圈",Toast.LENGTH_SHORT).show(); 
          break; 
        case R.id.qqhaoyou: 
          Toast.makeText(MainActivity.this,"QQ好友",Toast.LENGTH_SHORT).show(); 
          break; 
        case R.id.qqkongjian: 
          Toast.makeText(MainActivity.this,"QQ空间",Toast.LENGTH_SHORT).show(); 
          break; 
        default: 
          break; 
      } 
    } 
 
  }; 
} 

布局文件--popupWindow布局

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
       android:layout_width="match_parent" 
 
       android:layout_height="match_parent" 
       > 
  <TextView 
    android:layout_width="match_parent" 
    android:alpha="0.2" 
    android:layout_height="match_parent" 
    android:layout_above="@+id/ll"/> 
 
<LinearLayout 
  android:id="@+id/ll" 
  android:layout_width="match_parent" 
  android:layout_height="wrap_content" 
  android:layout_alignParentBottom="true" 
  android:orientation="vertical"> 
  <LinearLayout 
    android:paddingBottom="30dp" 
    android:id="@+id/share_ll" 
    android:paddingTop="20dp" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:paddingRight="20dp" 
    android:background="#ebebeb" 
    android:paddingLeft="20dp" 
    android:orientation="horizontal" 
    > 
  <LinearLayout 
    android:id="@+id/weixinghaoyou" 
    android:layout_width="0dp" 
    android:layout_weight="1" 
    android:layout_height="wrap_content" 
    android:orientation="vertical" 
    > 
 
    <ImageView 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_gravity="center" 
      android:background="@mipmap/icon_weixin_fenxiang"/> 
 
    <TextView 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:gravity="center" 
      android:onClick="share" 
      android:layout_gravity="center" 
      android:layout_marginTop="10dp" 
      android:text="微信好友" 
      android:textColor="#000000"/> 
  </LinearLayout> 
  <LinearLayout 
    android:id="@+id/pengyouquan" 
    android:layout_width="0dp" 
    android:layout_weight="1" 
    android:layout_height="wrap_content" 
    android:orientation="vertical" 
    > 
 
    <ImageView 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_gravity="center" 
      android:background="@mipmap/icon_quan"/> 
 
    <TextView 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:gravity="center" 
      android:onClick="share" 
      android:layout_gravity="center" 
      android:layout_marginTop="10dp" 
      android:text="朋友圈" 
      android:textColor="#000000"/> 
  </LinearLayout> 
  <LinearLayout 
    android:id="@+id/qqhaoyou" 
    android:layout_width="0dp" 
    android:layout_weight="1" 
    android:layout_height="wrap_content" 
    android:orientation="vertical" 
    > 
 
    <ImageView 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_gravity="center" 
      android:background="@mipmap/icon_qq_fenxiang"/> 
 
    <TextView 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:gravity="center" 
      android:onClick="share" 
      android:layout_gravity="center" 
      android:layout_marginTop="10dp" 
      android:text="QQ" 
      android:textColor="#000000"/> 
  </LinearLayout> 
  <LinearLayout 
    android:id="@+id/qqkongjian" 
    android:layout_width="0dp" 
    android:layout_weight="1" 
    android:layout_height="wrap_content" 
    android:orientation="vertical" 
    > 
 
    <ImageView 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_gravity="center" 
      android:background="@mipmap/icon_kongjian"/> 
 
    <TextView 
 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:gravity="center" 
      android:onClick="share" 
      android:layout_gravity="center" 
      android:layout_marginTop="10dp" 
      android:text="QQ空间" 
      android:textColor="#000000"/> 
  </LinearLayout> 
  </LinearLayout> 
 
  <TextView 
    android:id="@+id/line" 
    android:layout_width="match_parent" 
    android:layout_height="0.5dp" 
    android:layout_below="@+id/share_ll" 
    android:background="#000000"/> 
<TextView 
  android:id="@+id/share_cancle" 
  android:layout_width="match_parent" 
  android:layout_height="wrap_content" 
  android:gravity="center" 
  android:textSize="20sp" 
  android:layout_below="@+id/line" 
  android:background="#f5f3f3" 
  android:paddingBottom="20dp" 
  android:paddingTop="20dp" 
  android:text="取消"/> 
</LinearLayout> 
</RelativeLayout> 

mainActivity的布局文件

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout 
  xmlns:android="http://schemas.android.com/apk/res/android" 
  xmlns:tools="http://schemas.android.com/tools" 
  android:id="@+id/activity_main" 
  android:layout_width="match_parent" 
  android:layout_height="match_parent" 
  tools:context="com.duanlian.popupwindowdemo.MainActivity"> 
 
  <Button 
    android:id="@+id/share" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:text="点击弹出"/> 
</RelativeLayout> 

demo下载地址:Android PopupWindow弹出分享

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。

android PopupWindow

PopupWindow window = new PopupWindow(activity);//的到对象

2

window.setBackgroundDrawable(activity.getResources().getDrawable(R.drawable.configlistviewbg));//设置背景      
        //设置PopupWindow显示和隐藏时的动画
        window.setAnimationStyle(R.style.AnimationFade);
        View view=LayoutInflater.from(activity).inflate(joker.housemananger.activity.R.layout.addhouseactivity_popuwindow, null,true);//将popu的布局文件实例出
        long wid=activity.getWindowManager().getDefaultDisplay().getWidth(); //的到屏幕的宽
        long hd=activity.getWindowManager().getDefaultDisplay().getHeight();//得到屏幕的高
        View call=view.findViewById(R.id.addhouse_popuwindow_bt_callphone);//以下设置 布局文件上控件的监听器,因为这个类就继承了OnclickListener接口就直接this了
        call.setOnClickListener(this);
        View mess=view.findViewById(R.id.addhouse_popuwindow_bt_message);
        mess.setOnClickListener(this);
        View cancel=view.findViewById(R.id.addhouse_popuwindow_bt_cancel);
        cancel.setOnClickListener(this);                
        window.setWidth(Integer.parseInt(wid+""));//设置popupWindow高度
        window.setHeight(Integer.parseInt(hd/2+"")-100);//设置高度
        window.setContentView(view);//设置popupwindows的内容   样子
            //设置PopupWindow外部区域是否可触摸
        window.setOutsideTouchable(false);
        window.setFocusable(true); //设置 popupwindows获得焦点,以此来响应 返回键

3


windows.showAsDropDown(View) //显示windows,从上面向下显示
windows.showAsDropDown(View,0,0) //同第一个,加上两个偏移量,横纵轴的偏移
windows.showAtLocation(view, Gravity.BOTTOM, 0, 0); //设置popupwindow出现的位置,参1 设置出现在哪个view内,参2出现的位置,冲对面展开,参3参4 横纵轴的偏移

4

popupwindow.dismiss(); //关闭popupwindows

5 popupwindow 的动画 style 的 item 的 syle 的值

<item name="android:windowEnterAnimation">@anim/anim_down_in</item>
    	<item name="android:windowExitAnimation">@anim/anim_down_out</item>





Android PopupWindow 实现自定义菜单弹窗效果

先看最终效果图:
请输入图片描述
原理一个将PopupWindow绑在一个TextView上,处理TextView点击事件来弹框,右边EditText实现输入框,把EditText拿上来是因为在实习过程中碰到不少细节问题。代码:
main.xml //主页面布局

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/bgtitlebar"
    android:orientation="horizontal"
    android:padding="10dp" >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center_vertical" >

        <Button
            android:id="@+id/btn_header_back"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/btn_back"
            android:onClick="back" />
    </LinearLayout>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:layout_marginLeft="10dp"
        android:text="@string/txt_search"
        android:textSize="18sp" />
</RelativeLayout>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/bg_divide_line_search" >

    <LinearLayout
        android:id="@+id/ll_search_txt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="6dp"
        android:background="@drawable/bg_tv_search_category" >//因为一个控件只能有一张背景图片,所以把“资讯”的另一张背景图片放在布局上

        <TextView
            android:id="@+id/search_category"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="3dp"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="3dp"
            android:clickable="true"
            android:drawableRight="@drawable/bg_tv_search_pop"//这个属性可将图片放在控件的左侧
            android:text="@string/message"
            android:textColor="@color/blue"
            android:textSize="19sp" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="18dp"
        android:layout_toRightOf="@id/ll_search_txt"
        android:background="@drawable/bg_edt_search"
        android:layout_marginTop="9dp"
        >
        <EditText
            android:id="@+id/input_search_cagegory"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingLeft="5dp"
            android:background="@drawable/bg_edt_search"
            android:ems="10"
            android:drawableLeft="@drawable/bg_edt_search_icon  
            android:hint="@string/input_search_txt"
            android:singleLine="true" />
    </LinearLayout>
</RelativeLayout>

popup_item.xml // PopupWindow 弹框内容,这里只是简单的TextView,涉及ListView的话要复杂些

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
    android:id="@+id/search_picture"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/picture"
    android:clickable="true"
    android:textSize="19sp"
    android:background="@drawable/bg_search_picture"
    />
 <TextView
    android:id="@+id/search_video"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/video"
    android:clickable="true"
    android:textSize="19sp"
    android:background="@drawable/bg_search_video"
    />
  <TextView
    android:id="@+id/search_message"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/message"
    android:clickable="true"
    android:textSize="19sp"
    android:background="@drawable/bg_search_message"
    />


main.java

public class SearchActivity extends Activity {
private PopupWindow window = null;
private LayoutInflater inflater;
private TextView txt_choosecategory;
private TextView message;
private TextView picture;
private TextView video;
private EditText edt_inputcagegory;
private Button btn_header_back;
private View view;
private ListView listView;
private String return_result;
private String category_id;
private String keyword;
    private SearchTask searchTask;
private String category;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_search);
    initHeader();
    initBodyer();
}

private boolean isInput() {
    if (isNullorSpace(edt_inputcagegory.getText().toString())) {
        return false;
    }
    return true;
}

private void initBodyer() {
//      final InputMethodManager imm = (InputMethodManager)      //getSystemService(Context.INPUT_METHOD_SERVICE);
    txt_choosecategory = (TextView) findViewById(R.id.search_category);
    edt_inputcagegory = (EditText) findViewById(R.id.input_search_cagegory);
    edt_inputcagegory.setImeOptions(EditorInfo.IME_ACTION_SEARCH); //这行代码的作用是把键盘右下角的“回车”键变成“搜索”键
    txt_choosecategory.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (window != null) {  //一定要先判断是否为空!
                if (window.isShowing()) {//isShowing()方法判断当前是否已经弹窗,返回true则关闭PopupWindow
                    window.dismiss();
                    window = null;
                }
            } else {
                showWindow();实际这里是实现点击一次弹出PopupWindow,再点击一次关闭掉。
            }

        }
    });
    edt_inputcagegory
            .setOnEditorActionListener(new OnEditorActionListener() {

                @Override
                public boolean onEditorAction(TextView v, int actionId,
                        KeyEvent event) {//对键盘的搜索键监听事件
                    if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                        if (isInput()) {
                            search();
                        } else {
//edt_inputcagegory.requestFocus();                                                          //imm.showSoftInputFromInputMethod(edt_inputcagegory.getWindowToken(), 0);
Toast.makeText(Main.this,"搜索内容不能为空",Toast.LENGH_SHORT);                         

                        }
                    }

                    return false;
                }
            });
}

private void initHeader() {
    btn_header_back = (Button) findViewById(R.id.btn_header_back);
    btn_header_back.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            finish();
        }
    });
}
    private boolean isNullorSpace(String str) {
    if (!"".equals(str.trim()) & (str != null))
        return false;
    return true;
}

private void search() {
    //Handle search
}

private void showWindow() {
    inflater = (LayoutInflater) this
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    view = inflater.inflate(R.layout.item_search_category, null, false);//加载布局
    message = (TextView) view.findViewById(R.id.search_message);
    video = (TextView) view.findViewById(R.id.search_video);
    picture = (TextView) view.findViewById(R.id.search_picture);
    message.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            txt_choosecategory.setText(R.string.message);  //错误代码
            window.dismiss();
            window = null;
        }
    });
    video.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            txt_choosecategory.setText(R.string.video);//错误代码
            window.dismiss();
            window = null;
        }
    });
    picture.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            txt_choosecategory.setText(R.string.picture);//错误代码
            window.dismiss();
            window = null;
        }
    });
    if (window == null) {
        window = new PopupWindow(view, LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT);//创建PopupWindow,第一个参数是将要展示的内容布局,第二、三个是布局大小(LayoutParamas.WRAP_CONTENT,LayoutParams.WRAP_CONTENT要求API >=11)
    }
    // int[] location = new int[2];
    // window.showAsDropDown(txt_choosecategory);
    // window.showAtLocation(txt_choosecategory, Gravity.NO_GRAVITY,
    // location[0], location[1]);
    window.showAtLocation(txt_choosecategory, Gravity.NO_GRAVITY, 15, 160);//设置PopupWindow位置,第一个参数是指定PopupWindow依附的View,第二个是坐标偏移量相对的起始点,Gravity.NO_GRAVITY= Gravity.LEFT | Gravity.TOP,最后两个是偏移量,这个写死了应该对屏幕适配不太好,而且很麻烦囧,暂时还没找到方便的方法..欢迎大侠指路.
}

需要注意的是:1.本人一开始用PopupWindow就曾经报错: "Unable to add window -- token null is not valid",原因在stackoverflow上找到:To avoid BadTokenException, you need to defer showing the popup until after all the lifecycle methods are called (-> activity window is displayed),简而言之就是要在布局全部加载完之后再去加载PopupWindow,显示PopupWindow过早就会直接crash.
2.在Activity取出string资源文件值,textView.setText(R.string.XXX)是错误的写法应g改为-->textView.setText(getString(R.string.xxx))或者getResources().getString(R.string.xxx),原因:http://stackoverflow.com/questions/11536326/android-settext-r-string-values
描述
(第一句一语道破天机,R.string.xxx仅仅是资源的ID,所以R.String.xxx得到的是资源的编号)

Android Popupwindow 拖动

 

   关于View的拖动你们应该比较了解了,好比对一个控件IamgeView拖动,或者一个视图View拖动,实现方式也很容易,继承OnTouchListener接口,而后重写onTouch方法,在触屏事件进行处理便可。可是Popupwindow如何实现拖动呢,咱们都知道它和普通的View不同,由于它不是继承于View类的,可是它的实现倒是和View密切相关的,由于咱们都知道Android视图的显示都是由View来处理的,因此必定离不开它。从Popupwindow的实现就能够看出来,ide

 

import com.android.internal.R;

import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.StateListDrawable;
import android.os.Build;
import android.os.IBinder;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnScrollChangedListener;
import android.view.WindowManager;

import java.lang.ref.WeakReference;
  上面是它的导包状况,基本上不是和View相关,就是和绘图相关。所以关于Popupwindow的拖动这一块,也和View有联系。首先看一下它的API,看一看有没有和View移动、变化相关的方法,果真在最后有几个update()方法,以下:

 

  update()方法用来更新Popupwindow的位置和大小的,那么问题就好解决了。看代码:布局

 

package com.example.drag_and_drop_movablepopupwindow;

import android.support.v7.app.ActionBaractivity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.TextView;

public class MainActivity extends ActionBaractivity {

	private Button btnopenPopup;

	private int mCurrentX;
	private int mCurrentY;
	
	private PopupWindow mPopup;
	 
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_main);
		btnopenPopup = (Button) findViewById(R.id.openpopup);
		btnopenPopup.setonClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				creatPopubWindow_1();
			}
		});
	}

	/**
	 * 1
	 */
	private void creatPopubWindow_1() {
		LayoutInflater layoutInflater = (LayoutInflater) getBaseContext()
				.getSystemService(LAYOUT_INFLATER_SERVICE);
		View popupView = layoutInflater.inflate(R.layout.popup, null);
		final PopupWindow popupWindow = new PopupWindow(popupView,
				200, 200);

		Button btndismiss = (Button) popupView.findViewById(R.id.dismiss);
		btndismiss.setonClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View v) {
				popupWindow.dismiss();
			}
		});

		popupWindow.showAsDropDown(btnopenPopup, 50, 50);

		popupView.setonTouchListener(new OnTouchListener() {
			int orgX, orgY;
			int offsetX, offsetY;

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					orgX = (int) event.getX();
					orgY = (int) event.getY();
					break;
				case MotionEvent.ACTION_MOVE:
					offsetX = (int) event.getRawX() - orgX;
					offsetY = (int) event.getRawY() - orgY;
					popupWindow.update(offsetX, offsetY, -1, -1, true);
					break;
				}
				return true;
			}
		});
	}
}

  效果如图:ui

  首先对Popupwindow设置触摸事件,而后在回调方法中进行计算,若是手指拖动了Popupwindow,那么就调用update()方法来更新它的位置。有些同窗可能不太理解参数-1是什么意思,在上面的API中,写明的是宽和高,这里怎么变成-1了呢,看一下Popupwindow源代码就明白了。this

 

 

/**
     * <p>Updates the position and the dimension of the popup window. Width and
     * height can be set to -1 to update location only.  Calling this function
     * also updates the window with the current popup state as
     * described for {@link #update()}.</p>
     *
     * @param x the new x location
     * @param y the new y location
     * @param width the new width, can be -1 to ignore
     * @param height the new height, can be -1 to ignore
     * @param force reposition the window even if the specified position
     *              already seems to correspond to the LayoutParams
     */
    public void update(int x, int y, int width, int height, boolean force) {
        if (width != -1) {
            mLastWidth = width;
            setWidth(width);
        }

        if (height != -1) {
            mLastHeight = height;
            setHeight(height);
        }

        if (!isShowing() || mContentView == null) {
            return;
        }

        WindowManager.LayoutParams p = (WindowManager.LayoutParams) mPopupView.getLayoutParams();

        boolean update = force;

        final int finalWidth = mWidthMode < 0 ? mWidthMode : mLastWidth;
        if (width != -1 && p.width != finalWidth) {
            p.width = mLastWidth = finalWidth;
            update = true;
        }

        final int finalHeight = mHeightMode < 0 ? mHeightMode : mLastHeight;
        if (height != -1 && p.height != finalHeight) {
            p.height = mLastHeight = finalHeight;
            update = true;
        }

        if (p.x != x) {
            p.x = x;
            update = true;
        }

        if (p.y != y) {
            p.y = y;
            update = true;
        }

        final int newAnim = computeAnimationResource();
        if (newAnim != p.windowAnimations) {
            p.windowAnimations = newAnim;
            update = true;
        }

        final int newFlags = computeFlags(p.flags);
        if (newFlags != p.flags) {
            p.flags = newFlags;
            update = true;
        }

        if (update) {
            setLayoutDirectionFromAnchor();
            mWindowManager.updateViewLayout(mPopupView, p);
        }
    }
  前两个if判断已经说得很清楚了,若是参数是-1的话,就不改变Popupwindow的大小了,由于咱们只是移动位置,因此才这样写。那关于Popupwindow的移动最后是怎么实现的呢,能够看出就是调用WindowManager的updateViewLayout()方法,这个方法在WindowManager中并无实现,它是ViewManager接口里面的方法,WindowManager继承了ViewManager。说到ViewManager,它里面定义的方法都很经常使用,看代码:

 

 

/** Interface to let you add and remove child views to an Activity. To get an instance
  * of this class, call {@link android.content.Context#getSystemService(java.lang.String) Context.getSystemService()}.
  */
public interface ViewManager
{
    /**
     * Assign the passed LayoutParams to the passed View and add the view to the window.
     * <p>Throws {@link android.view.WindowManager.BadTokenException} for certain programming
     * errors, such as adding a second view to a window without removing the first view.
     * <p>Throws {@link android.view.WindowManager.InvaliddisplayException} if the window is on a
     * secondary {@link display} and the specified display can't be found
     * (see {@link android.app.Presentation}).
     * @param view The view to be added to this window.
     * @param params The LayoutParams to assign to view.
     */
    public void addView(View view, ViewGroup.LayoutParams params);
    public void updateViewLayout(View view, ViewGroup.LayoutParams params);
    public void removeView(View view);
}
  这下你们应该明了,咱们常常用的addView、removeView方法就是在这里面定义的,那么谁去实现呢?就是Layout控件,好比LinearLayout、RelativeLayout等,因此咱们刚才用的updateViewLayout()方法也是在xml布局文件中的layout定义好的。    

Android PopupWindow实现右侧、左侧和底部弹出菜单

Android PopupWindow实现右侧、左侧和底部弹出菜单

本教程为大家分享了Android PopupWindow弹出菜单的具体代码,供大家参考,具体内容如下

项目代码:http://xiazai.jb51.net/201611/yuanma/PopupLeftMenu(jb51.net).rar

项目SDK是5.1,建议将代码拷到自己的工程中去

代码如下:

MainActivity类:

package com.example.popupleftmenu; 
 
import android.app.Activity; 
import android.content.Context; 
import android.graphics.drawable.ColorDrawable; 
import android.os.Bundle; 
import android.view.Gravity; 
import android.view.MotionEvent; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.view.View.OnTouchListener; 
import android.view.ViewGroup.LayoutParams; 
import android.view.WindowManager; 
import android.widget.Button; 
import android.widget.PopupWindow; 
import android.widget.Toast; 
 
public class MainActivity extends Activity { 
 
 private Context context = null; 
 private PopupWindow popupWindow; 
 private int from = 0; 
  
 @Override 
 protected void onCreate(Bundle savedInstanceState) { 
  super.onCreate(savedInstanceState); 
  context = this; 
  setContentView(R.layout.activity_main); 
  Button popLeftBtn = (Button)findViewById(R.id.pop_left_btn); 
  Button popRightBtn = (Button)findViewById(R.id.pop_right_btn); 
  Button popBottomBtn = (Button)findViewById(R.id.pop_bottom_btn); 
  popLeftBtn.setonClickListener(popClick); 
  popRightBtn.setonClickListener(popClick); 
  popBottomBtn.setonClickListener(popClick); 
 } 
 
  
 OnClickListener popClick = new OnClickListener() { 
   
  @Override 
  public void onClick(View v) { 
   switch(v.getId()){ 
    case R.id.pop_left_btn:{ 
     from = Location.LEFT.ordinal(); 
     break; 
    } 
    case R.id.pop_right_btn:{ 
     from = Location.RIGHT.ordinal(); 
     break; 
    } 
    case R.id.pop_bottom_btn:{ 
     from = Location.BottOM.ordinal(); 
     break; 
    } 
   } 
    
   //调用此方法,menu不会顶置 
   //popupWindow.showAsDropDown(v); 
   initPopupWindow(); 
    
  } 
 }; 
 /** 
  * 添加新笔记时弹出的popWin关闭的事件,主要是为了将背景透明度改回来 
  * 
  */ 
 class popupdismissListener implements PopupWindow.OndismissListener{ 
 
  @Override 
  public void ondismiss() { 
   backgroundAlpha(1f); 
  } 
   
 } 
  
  
 protected void initPopupWindow(){ 
  View popupWindowView = getLayoutInflater().inflate(R.layout.pop,null); 
  //内容,高度,宽度 
  if(Location.BottOM.ordinal() == from){ 
   popupWindow = new PopupWindow(popupWindowView,LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT,true); 
  }else{ 
   popupWindow = new PopupWindow(popupWindowView,true); 
  } 
  //动画效果 
  if(Location.LEFT.ordinal() == from){ 
   popupWindow.setAnimationStyle(R.style.AnimationLeftFade); 
  }else if(Location.RIGHT.ordinal() == from){ 
   popupWindow.setAnimationStyle(R.style.AnimationRightFade); 
  }else if(Location.BottOM.ordinal() == from){ 
   popupWindow.setAnimationStyle(R.style.AnimationBottomFade); 
  } 
  //菜单背景色 
  ColorDrawable dw = new ColorDrawable(0xffffffff); 
  popupWindow.setBackgroundDrawable(dw); 
  //宽度 
  //popupWindow.setWidth(LayoutParams.WRAP_CONTENT); 
  //高度 
  //popupWindow.setHeight(LayoutParams.FILL_PARENT); 
  //显示位置 
  if(Location.LEFT.ordinal() == from){ 
   popupWindow.showAtLocation(getLayoutInflater().inflate(R.layout.activity_main,null),Gravity.LEFT,500); 
  }else if(Location.RIGHT.ordinal() == from){ 
   popupWindow.showAtLocation(getLayoutInflater().inflate(R.layout.activity_main,Gravity.RIGHT,500); 
  }else if(Location.BottOM.ordinal() == from){ 
   popupWindow.showAtLocation(getLayoutInflater().inflate(R.layout.activity_main,Gravity.BottOM|Gravity.CENTER_HORIZONTAL,0); 
  } 
  //设置背景半透明 
  backgroundAlpha(0.5f); 
  //关闭事件 
  popupWindow.setondismissListener(new popupdismissListener()); 
   
  popupWindowView.setonTouchListener(new OnTouchListener() { 
    
   @Override 
   public boolean onTouch(View v,MotionEvent event) { 
    /*if( popupWindow!=null && popupWindow.isShowing()){ 
     popupWindow.dismiss(); 
     popupWindow=null; 
    }*/ 
    // 这里如果返回true的话,touch事件将被拦截 
    // 拦截后 PopupWindow的onTouchEvent不被调用,这样点击外部区域无法dismiss 
    return false; 
   } 
  }); 
   
  Button open = (Button)popupWindowView.findViewById(R.id.open); 
  Button save = (Button)popupWindowView.findViewById(R.id.save); 
  Button close = (Button)popupWindowView.findViewById(R.id.close); 
   
   
  open.setonClickListener(new OnClickListener() { 
    
   @Override 
   public void onClick(View v) { 
    Toast.makeText(context,"Open",Toast.LENGTH_LONG).show(); 
    popupWindow.dismiss(); 
   } 
  }); 
   
  save.setonClickListener(new OnClickListener() { 
    
   @Override 
   public void onClick(View v) { 
    Toast.makeText(context,Toast.LENGTH_LONG).show(); 
    popupWindow.dismiss(); 
   } 
  }); 
   
  close.setonClickListener(new OnClickListener() { 
    
   @Override 
   public void onClick(View v) { 
    Toast.makeText(context,Toast.LENGTH_LONG).show(); 
    popupWindow.dismiss(); 
   } 
  }); 
 } 
  
 /** 
  * 设置添加屏幕的背景透明度 
  * @param bgalpha 
  */ 
 public void backgroundAlpha(float bgalpha) 
 { 
  WindowManager.LayoutParams lp = getwindow().getAttributes(); 
  lp.alpha = bgalpha; //0.0-1.0 
  getwindow().setAttributes(lp); 
 } 
 /** 
  * 菜单弹出方向 
  * 
  */ 
 public enum Location { 
 
  LEFT,RIGHT,TOP,BottOM; 
   
 } 
} 

两个布局文件:

1.activity_main.xml,就三个Button

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
 xmlns:tools="http://schemas.android.com/tools" 
 android:layout_width="fill_parent" 
 android:layout_height="fill_parent" 
 android:orientation="vertical"> 
 
 <Button 
  android:id="@+id/pop_left_btn" 
  android:layout_width="fill_parent" 
  android:layout_height="wrap_content" 
  android:text="@string/pop_left"/> 
  
 <Button 
  android:id="@+id/pop_right_btn" 
  android:layout_width="fill_parent" 
  android:layout_height="wrap_content" 
  android:text="@string/pop_right"/> 
  
 <Button 
  android:id="@+id/pop_bottom_btn" 
  android:layout_width="fill_parent" 
  android:layout_height="wrap_content" 
  android:text="@string/pop_bottom"/> 
  
 
</LinearLayout>

2. pop.xml,也是三个Button,可以自己修改

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
 android:layout_width="fill_parent" 
 android:layout_height="fill_parent" 
 android:orientation="vertical" > 
  
 <!-- <LinearLayout 
  android:layout_width="wrap_content" 
  android:layout_height="fill_parent" 
  android:orientation="vertical" 
  android:background="#ffffff"> --> 
   
  <Button android:id="@+id/open" 
   android:layout_width="fill_parent" 
   android:layout_height="wrap_content" 
   android:text="@string/open"/> 
   
  <Button android:id="@+id/save" 
   android:layout_width="fill_parent" 
   android:layout_height="wrap_content" 
   android:text="@string/save"/> 
   
  <Button android:id="@+id/close" 
   android:layout_width="fill_parent" 
   android:layout_height="wrap_content" 
   android:text="@string/close"/> 
   
 <!-- </LinearLayout> --> 
  
</LinearLayout> 

strings.xml

<string name="pop_left">弹出左侧菜单</string> 
 <string name="pop_right">弹出右侧菜单</string> 
 <string name="pop_bottom">弹出底部菜单</string> 
 <string name="open">打开</string> 
 <string name="save">保存</string> 
 <string name="close">关闭</string> 

styles.xml

<style name="AnimationLeftFade"> 
  <item name="android:windowEnteranimation">@anim/in_lefttoright</item> 
  <item name="android:windowExitAnimation">@anim/out_righttoleft</item> 
 </style> 
  
 <style name="AnimationRightFade"> 
  <item name="android:windowEnteranimation">@anim/in_righttoleft</item> 
  <item name="android:windowExitAnimation">@anim/out_lefttoright</item> 
 </style> 
  
 <style name="AnimationBottomFade"> 
  <item name="android:windowEnteranimation">@anim/in_bottomtotop</item> 
  <item name="android:windowExitAnimation">@anim/out_toptobottom</item> 
 </style> 

左边弹出菜单动画文件:

in_lefttoright.xml:从左边入

<?xml version="1.0" encoding="utf-8"?> 
<set xmlns:android="http://schemas.android.com/apk/res/android"> 
  
 <translate 
  android:fromXDelta="-100%" 
  android:toXDelta="0" 
  android:duration="500"/> 
  
</set> 

out_righttoleft.xml:从右边出

<?xml version="1.0" encoding="utf-8"?> 
<set xmlns:android="http://schemas.android.com/apk/res/android"> 
  
 <translate android:fromXDelta="0" 
  android:toXDelta="-100%" 
  android:duration="500"/> 
 
</set> 

其他动画文件自己参考写,就是fromXDelta, fromYDelta, toXDelta和toYDelta使用。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。

我们今天的关于Android自定义PopupWindow仿点击弹出分享功能android自定义弹窗点击事件的分享已经告一段落,感谢您的关注,如果您想了解更多关于android PopupWindow、Android PopupWindow 实现自定义菜单弹窗效果、Android Popupwindow 拖动、Android PopupWindow实现右侧、左侧和底部弹出菜单的相关信息,请在本站查询。

本文标签: