题目:
创建一个项目,里面有一个按钮,点击按钮弹出popwindow,高150 宽200,popwindow中有3个按钮,点击按钮 改变背景颜色
代码:
布局文件:
main.xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/linearLayout" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.mrzhao.examdemo.MainActivity"> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="onBtClick" android:text="点击弹出PopupWindow" /> </LinearLayout>
pop_layout.xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <!--50px是因为 题目要求高度是150 所以平均下来每个占据 50px--> <Button android:id="@+id/bt_red" android:layout_width="match_parent" android:layout_height="50px" android:text="红色" /> <Button android:id="@+id/bt_blue" android:layout_width="match_parent" android:layout_height="50px" android:text="蓝色" /> <Button android:id="@+id/bt_green" android:layout_width="match_parent" android:layout_height="50px" android:text="绿色" /> </LinearLayout>
MainActivity.java:
package com.mrzhao.examdemo; import android.graphics.Color; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.PopupWindow; public class MainActivity extends AppCompatActivity implements View.OnClickListener{ private PopupWindow popupWindow; private LinearLayout linearLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //实例化根视图 linearLayout = (LinearLayout) findViewById(R.id.linearLayout); } public void onBtClick(View view) { //点击弹出PopupWindow View popView = LayoutInflater.from(this).inflate(R.layout.pop_layout, null); //实例化菜单中的按钮 Button redBt = (Button) popView.findViewById(R.id.bt_red); Button blueBt = (Button) popView.findViewById(R.id.bt_blue); Button greenBt = (Button) popView.findViewById(R.id.bt_green); //设置监听事件 redBt.setOnClickListener(this); blueBt.setOnClickListener(this); greenBt.setOnClickListener(this); //实例化 弹出框 popupWindow = new PopupWindow(popView,200,150); //显示出来 popupWindow.showAsDropDown(view); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.bt_red: //修改背景颜色 linearLayout.setBackgroundColor(Color.RED); break; case R.id.bt_blue: //修改背景颜色 linearLayout.setBackgroundColor(Color.BLUE); break; case R.id.bt_green: //修改背景颜色 linearLayout.setBackgroundColor(Color.GREEN); break; } //弹出框消失 popupWindow.dismiss(); } }