今天讲一下点击之后下拉的弹出框,类似于下拉列表的那种,
1.首先要自定义弹出框的样式,定义一个layout文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/tv_pop"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20sp"
android:textColor="@color/colorBlue"
android:text="好"
android:gravity="center"
android:paddingBottom="8dp"
android:paddingTop="8dp"/>
<view
android:layout_width="match_parent"
android:layout_height="0.5dp"
android:background="@color/colorAccent"></view>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20sp"
android:textColor="@color/colorBlue"
android:text="还行"
android:gravity="center"
android:paddingBottom="8dp"
android:paddingTop="8dp"/>
<view
android:layout_width="match_parent"
android:layout_height="0.5dp"
android:background="@color/colorAccent"></view>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20sp"
android:textColor="@color/colorBlue"
android:text="不好"
android:gravity="center"
android:paddingBottom="8dp"
android:paddingTop="8dp"/>
</LinearLayout>
效果如下图所示:
2.然后在声明一个按钮,点击之后弹出,声明按钮的代码如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".PopupWindowActivity"
android:orientation="vertical">
<Button
android:id="@+id/btn_pop"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:text="POP"
android:layout_gravity="center_horizontal"
android:layout_marginTop="50dp"
/>
</LinearLayout>
3.在Activity文件中声明弹出操作
package com.example.startfrompop;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.PopupWindow;
public class PopupWindowActivity extends AppCompatActivity {
Button bt1;
PopupWindow pop1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_popup_window);
bt1=findViewById(R.id.btn_pop);
bt1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
View view1=getLayoutInflater().inflate(R.layout.layout_pop,null); //引用自定义的样式
pop1=new PopupWindow(view1,bt1.getWidth(), ViewGroup.LayoutParams.WRAP_CONTENT); //新建一个PopupWindow
pop1.showAsDropDown(bt1);
}
});
}
}