简单理解该组件就是类似弹出层的一种android组件,这种组件类似QQ的状态修改的弹出,下面就来看下这类弹出窗怎么实现
1.对于弹出窗的内容,简单的做法就是写一个布局xml文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="@+id/popstatus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="选择用户状态"
/>
<RadioGroup
android:id="@+id/changestatus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:checkedButton="@+id/online"
>
<RadioButton
android:id="@+id/online"
android:text="在线"
/>
<RadioButton
android:id="@+id/offline"
android:text="离线"
/>
<RadioButton
android:id="@+id/hidden"
android:text="隐身"
/>
</RadioGroup>
</LinearLayout>
2.下面就是主界面的配置文件了,这里就定义一个textview和一个按钮,点击按钮就出现弹出窗,点击单选按钮textview的内容随之改变
(1)读取布局文件
(2)实例化PopupWindow,添加单选按钮事件处理
下面是主界面文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="@+id/status"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="在线"
/>
<Button
android:id="@+id/updatestatus"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="修改状态"/>
</LinearLayout>
下面则是最主要的逻辑代码
package org.lxh.popwin;
import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
public class PopwinActivity extends Activity {
private Button updatestatus = null;
private PopupWindow popWin = null;
private View view = null;
private RadioGroup changestatus = null;
private TextView status = null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
status = (TextView) this.findViewById(R.id.status);
updatestatus = (Button) this.findViewById(R.id.updatestatus);
updatestatus.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
LayoutInflater flate = LayoutInflater.from(PopwinActivity.this);
view = flate.inflate(R.layout.popwin, null);
//实例化PopupWindow
popWin = new PopupWindow(view, 300, 200);
changestatus = (RadioGroup) view
.findViewById(R.id.changestatus);
// 单选改变事件
changestatus
.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group,
int checkedId) {
// 取得单选按钮
RadioButton rButton = (RadioButton) view
.findViewById(group
.getCheckedRadioButtonId());
status.setText(rButton.getText().toString());
//关闭弹出窗口
popWin.dismiss();
}
});
//显示弹出窗口
popWin.showAtLocation(updatestatus, Gravity.CENTER, 0, 0);
}
});
}
}
很简单吧,看下效果图吧