PopuWindow实现侧滑菜单

Activity中的代码如下:

package company.com.popuwindow;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.PopupWindow;

import java.util.zip.Inflater;

public class MainActivity extends Activity{
    private Button btn;
    private PopupWindow popupWindow;
    private View contentView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn= (Button) findViewById(R.id.btn_popuwindow);
        addListener();
        initpopuWindow();
    }

    private void addListener() {
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (popupWindow.isShowing()){popupWindow.dismiss();}
                popupWindow.showAtLocation(contentView, Gravity.RIGHT, 0, 0);
            }
        });
    }

    private void initpopuWindow() {
        LayoutInflater inflater= (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        contentView=inflater.inflate(R.layout.subitem,null);
        contentView.setFocusable(true);
        popupWindow=new PopupWindow(contentView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(false);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));
        popupWindow.setAnimationStyle(R.style.PopuWindow_left);
    }

}

此代码中的setBackgroundDrawable(new BitmapDrawable())必须设置,不然点击PopuWindow之外的任何地方都不会收起PopuWindow,当然为了不影响样式可以设置为setBackgroundDrawable(new ColorDrawable(0x00000000));此时背景不为空但是是透明的不会影响效果。

点击此处下载完整项目代码。

你可能感兴趣的:(PopuWindow实现侧滑菜单)