<?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" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="请选择" /> <RadioGroup android:id="@+id/rg" android:layout_width="wrap_content" android:layout_height="wrap_content" > <RadioButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="离线" /> <RadioButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="隐身" /> <RadioButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="在线" /> </RadioGroup> </LinearLayout>
弹出窗口的布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:id="@+id/show" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="在线" /> <Button android:id="@+id/btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="状态" /> </LinearLayout>
主布局
package com.example.popwindow; import android.os.Bundle; import android.app.Activity; import android.view.Gravity; import android.view.LayoutInflater; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.PopupWindow; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.RadioGroup.OnCheckedChangeListener; import android.widget.TextView; public class MainActivity extends Activity { private TextView show; private RadioGroup rg; private Button btn; private PopupWindow pop; private View v1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); show = (TextView) findViewById(R.id.show); btn = (Button) findViewById(R.id.btn); btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub LayoutInflater in = LayoutInflater.from(MainActivity.this); v1 = in.inflate(R.layout.pop, null);//得到布局 pop = new PopupWindow(v1,300,400 , true);//实例化弹出窗口 rg = (RadioGroup) v1.findViewById(R.id.rg);//设置单选按钮点击事件 rg.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { //声明单选按钮 并且实例化 RadioButton rd = (RadioButton) v1.findViewById(group.getCheckedRadioButtonId()); show.setText(rd.getText().toString()); //关闭弹出窗口 pop.dismiss(); } }); //显示弹出窗口 调用组件的按钮 位置 x,y pop.showAtLocation(btn, Gravity.CENTER, 0, 0); } }); } }