Android中PopupWindow的使用
- public class PopUpActivity extends Activity {
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- LayoutInflater inflater = LayoutInflater.from(this);
- // 引入窗口配置文件
- View view = inflater.inflate(R.layout.main2, null);
- // 創建PopupWindow對象
- final PopupWindow pop = new PopupWindow(view, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, false);
- Button btn = (Button) findViewById(R.id.btn);
- // 需要設置一下此參數,點擊外邊可消失
- pop.setBackgroundDrawable(new BitmapDrawable());
- //設置點擊窗口外邊窗口消失
- pop.setOutsideTouchable(true);
- // 設置此參數獲得焦點,否則無法點擊
- pop.setFocusable(true);
- btn.setOnClickListener(new OnClickListener() {
-
- @Override
- public void onClick(View v) {
- if(pop.isShowing()) {
- // 隱藏窗口,如果設置了點擊窗口外小時即不需要此方式隱藏
- pop.dismiss();
- } else {
- // 顯示窗口
- pop.showAsDropDown(v);
- }
-
- }
- });
- }
- }
main.xml
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical" >
-
- <Button
- android:id="@+id/btn"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="dianji" />
-
- </LinearLayout>
main2.xml
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical" >
-
- <Button
- android:id="@+id/a"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="AAAAA" />
-
- <Button
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="BBBBB" />
-
- <Button
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="CCCCC" />
-
- <Button
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="DDDDD" />
-
- </LinearLayout>
效果很不錯~~~
更多Android相關信息見Android 專題頁面 http://www.linuxidc.com/topicnews.aspx?tid=11