Android弹窗

发布于:2025-07-16 ⋅ 阅读:(16) ⋅ 点赞:(0)

PopupWindow(弹窗)

步骤:

1.创建PopupWindow对象实例

2.设置背景,注册事件监听器和添加动画

3.显示PopupWindow

(1)基础PopupWindow设置

在这里我们需要先创建我们自己的控件布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="wrap_content"
    android:padding="2dp"
    android:layout_height="wrap_content"
    android:background="@color/white"
    >
    <TextView
        android:id="@+id/choose"
        android:layout_width="60dp"
        android:layout_height="30dp"
        android:text="选择"
        android:textColor="#ffffff"
        android:gravity="center"
        android:background="#000000"/>
    <TextView
        android:id="@+id/allin"
        android:layout_width="60dp"
        android:layout_height="30dp"
        android:text="全选"
        android:textColor="#ffffff"
        android:gravity="center"
        android:background="#000000"/>
    <TextView
        android:id="@+id/copy"
        android:layout_width="60dp"
        android:layout_height="30dp"
        android:text="复制"
        android:textColor="#ffffff"
        android:gravity="center"
        android:background="#000000"/>
</LinearLayout>

然后创建按钮布局,实现在点击此按钮的时候,我们的弹框会弹出 这一个效果。

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <Button
        android:id="@+id/popupbtn"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:layout_marginRight="100dp"
        android:layout_marginLeft="100dp"
        android:text="pupop"
        android:textSize="20sp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>

 然后创建我们对应的activity,在这里我们实例化对象,指定视图对象,并展示。

public class PopupActivity extends AppCompatActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_showpupop);
        Button bt = findViewById(R.id.popupbtn);
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPopupWindow(view);
            }
        });
​
    }
public void showPopupWindow(View view){
        //准备弹窗要用的视图对象
        View v = LayoutInflater.from(this).inflate(R.layout.activity_popup,null);
        //1.实例化对象,参数1:view对象,参数2、3:弹窗的宽高,参数4能否获取焦点
        PopupWindow pw = new PopupWindow(v,490,80,true);
        //2.设置(可设置也可不设置)
        //设置弹框响应点击事件
        //3.展示,参数1(anchor):锚,参数2、3相对于x、y方向上的偏移量
        pw.showAsDropDown(view,40,0);

(2)设置样式

样式为可设置和可不设置,但一般都需要设置。

//设置背景,透明
        pw.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        //设置点击对象
        pw.setOutsideTouchable(true);

(3)设置点击事件

//为弹框文本添加点击事件
        v.findViewById(R.id.choose).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(PopupActivity.this, "choose", Toast.LENGTH_SHORT).show();
                pw.dismiss();
            }
        });
        v.findViewById(R.id.allin).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(PopupActivity.this, "allin", Toast.LENGTH_SHORT).show();
                pw.dismiss();
            }
        });
        v.findViewById(R.id.copy).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(PopupActivity.this, "copy", Toast.LENGTH_SHORT).show();
                pw.dismiss();
            }
        });

(4)弹窗动画

在res文件夹下创建anim文件夹,新建文件

可以设置弹框怎么出现,以及从哪里出现。

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

在theme下新增样式

  <style name="popup">
        <item name="android:windowEnterAnimation">@anim/popup</item>
    </style>

设置动画

//动画:1.创建动画资源,2.创建一个style应用动画资源,3.对当前的弹窗的动画风格设置为第二的资源索引
        pw.setAnimationStyle(R.style.popup);

最终代码:

package com.example.myapplication;
​
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.Toast;
​
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
​
public class PopupActivity extends AppCompatActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_showpupop);
        Button bt = findViewById(R.id.popupbtn);
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPopupWindow(view);
            }
        });
​
​
    }
    public void showPopupWindow(View view){
        //准备弹窗要用的视图对象
        View v = LayoutInflater.from(this).inflate(R.layout.activity_popup,null);
        //1.实例化对象,参数1:view对象,参数2、3:弹窗的宽高,参数4能否获取焦点
        PopupWindow pw = new PopupWindow(v,490,80,true);
        //2.设置(可设置也可不设置)
        //设置背景,透明
        pw.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        //设置点击对象
        pw.setOutsideTouchable(true);
        //动画:1.创建动画资源,2.创建一个style应用动画资源,3.对当前的弹窗的动画风格设置为第二的资源索引
        pw.setAnimationStyle(R.style.popup);
        //设置弹框响应点击事件
        //3.展示,参数1(anchor):锚,参数2、3相对于x、y方向上的偏移量
        pw.showAsDropDown(view,40,0);
​
        //为弹框文本添加点击事件
        v.findViewById(R.id.choose).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(PopupActivity.this, "choose", Toast.LENGTH_SHORT).show();
                pw.dismiss();
            }
        });
        v.findViewById(R.id.allin).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(PopupActivity.this, "allin", Toast.LENGTH_SHORT).show();
                pw.dismiss();
            }
        });
        v.findViewById(R.id.copy).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(PopupActivity.this, "copy", Toast.LENGTH_SHORT).show();
                pw.dismiss();
            }
        });
    }
}

ArrayAdapter

数组适配器,只能用来显示单一的文本。

构造方法:

ArrayAdapter(Context context,int resource,int textviewId,List<T>objects)

补充知识点:1.Activity启动方式

显示启动、隐式启动、startActivityForResult

显示启动,例如:

Intent it = new Intent(this,MainActivity.class); startActivity(it);

隐式启动:

//参数1:action是activity别名,参数2:Uri对象,打开路径,确定具体打开哪个activity Intent it = new Intent(Intent.ACTION_VIEW,Uri.parse("http://www.baidu.com"))//隐式打开浏览器 startActivity(it) Intent it1 = new Intent("")//隐式打开普通activity startActivity(it)

startActivityForResult

//如果是通过startActivityForResult的方法启动了第二个Activity,当第二个Activity处理结束后,再回到第一个Activity,会自动调用onActivityResult
    //在这个方法中我们可以处理第二个的返回的结果
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //resultCode:0,RESULT_CANCEL 取消 -1 RESULT_OK 正确处理完后返回
    }
Intent it = new Intent(this,MainActivity.class);
        startActivityForResult(it,1000);

在现代 Android 开发中,startActivityForResult(it, 1000) 方法的使用频率已经大幅降低,原因是 Google 在 AndroidX 库中引入了更优的替代方案。以下是详细分析:

Google 在 AndroidX 中推出了 Activity Result API(如registerForActivityResult),作为startActivityForResult的替代方案。它解决了前者的诸多问题:

  • 生命周期管理混乱:startActivityForResult依赖onActivityResult回调,若 Activity 因配置变更(如旋转)重建,可能导致结果丢失或逻辑混乱。

  • 代码耦合度高:回调方法集中处理所有返回结果,业务复杂时易臃肿。

  • 类型不安全:请求码(如 1000)需手动管理,易冲突。

// 注册回调
ActivityResultLauncher<Intent> launcher = registerForActivityResult(
    new ActivityResultContracts.StartActivityForResult(),
    result -> {
        if (result.getResultCode() == Activity.RESULT_OK) {
            Intent data = result.getData();
            // 处理返回数据
        }
    }
);
​
// 启动Activity
Intent it = new Intent(this, MainActivity.class);
launcher.launch(it);

补充知识点:2.Activity之间信息传递

1.传递简单内容

//传递简单数据
Intent it = new Intent(this,MainActivity.class);
it.putExtra("msg1","这是数据1");
it.putExtra("msg2",100);
startActivity(it);
//接收数据
Intent it = getIntent();
String msg1 = it.getStringExtra("msg1");
int msg2 = it.getIntExtra("msg2",0)

2.传递对象

注意这里传递对象的类里一定要implements Serializable,不然没办法传递对象

package com.example.myapplication;
​
import java.io.Serializable;
//序列化
//1.想把内存中的对象保存到第一个文件或数据库中时
//2.像利用套接字Socket在网络中传递对象
public class Student implements Serializable {
    private String name;
    private Integer age;
    private Integer id;
​
    public Integer getAge() {
        return age;
    }
​
    public void setAge(Integer age) {
        this.age = age;
    }
​
    public String getName() {
        return name;
    }
​
    public void setName(String name) {
        this.name = name;
    }
​
    public Integer getId() {
        return id;
    }
​
    public void setId(Integer id) {
        this.id = id;
    }
​
    public Student(String name, Integer age, Integer id) {
        this.name = name;
        this.age = age;
        this.id = id;
    }
}
传递数据
Intent it = new Intent(this,MainActivity.class);
Student s = new Student("张三",22,10086);
it.putExtra("stu",s);
//接收数据
Intent it = getIntent();
        Student student =(Student) it.getSerializableExtra("stu");


网站公告

今日签到

点亮在社区的每一天
去签到