android中弹出窗口,如何在Android中创建弹出窗口(PopupWindow)

如何制作一个简单的Android弹出窗口

这是一个更完整的例子。这是一个补充性答案,涉及一般情况下创建弹出窗口的过程,而不一定是OP问题的具体细节。(OP要求取消按钮,但这不是必需的,因为用户可以在屏幕上的任意位置单击以将其取消。)它看起来像下图。

设置弹出窗口的布局

向其中添加一个布局文件,res/layout该文件定义弹出窗口的外观。

popup_window.xml

xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:background="#62def8">

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_centerInParent="true"

android:layout_margin="30dp"

android:textSize="22sp"

android:text="This is a popup window."/>

充气并显示弹出窗口

这是示例中主要活动的代码。只要单击该按钮,弹出窗口就会膨胀并显示在活动上方。触摸屏幕上的任何位置均可关闭弹出窗口。

MainActivity.java

public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

}

public void onButtonShowPopupWindowClick(View view) {

// inflate the layout of the popup window

LayoutInflater inflater = (LayoutInflater)

getSystemService(LAYOUT_INFLATER_SERVICE);

View popupView = inflater.inflate(R.layout.popup_window, null);

// create the popup window

int width = LinearLayout.LayoutParams.WRAP_CONTENT;

int height = LinearLayout.LayoutParams.WRAP_CONTENT;

boolean focusable = true; // lets taps outside the popup also dismiss it

final PopupWindow popupWindow = new PopupWindow(popupView, width, height, focusable);

// show the popup window

// which view you pass in doesn't matter, it is only used for the window tolken

popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);

// dismiss the popup window when touched

popupView.setOnTouchListener(new View.OnTouchListener() {

@Override

public boolean onTouch(View v, MotionEvent event) {

popupWindow.dismiss();

return true;

}

});

}

}

而已。大功告成

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值