歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android中PopupWindow的使用

Android中PopupWindow的使用

日期:2017/3/1 10:21:03   编辑:Linux編程

Android中PopupWindow的使用

  1. public class PopUpActivity extends Activity {
  2. /** Called when the activity is first created. */
  3. @Override
  4. public void onCreate(Bundle savedInstanceState) {
  5. super.onCreate(savedInstanceState);
  6. setContentView(R.layout.main);
  7. LayoutInflater inflater = LayoutInflater.from(this);
  8. // 引入窗口配置文件
  9. View view = inflater.inflate(R.layout.main2, null);
  10. // 創建PopupWindow對象
  11. final PopupWindow pop = new PopupWindow(view, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, false);
  12. Button btn = (Button) findViewById(R.id.btn);
  13. // 需要設置一下此參數,點擊外邊可消失
  14. pop.setBackgroundDrawable(new BitmapDrawable());
  15. //設置點擊窗口外邊窗口消失
  16. pop.setOutsideTouchable(true);
  17. // 設置此參數獲得焦點,否則無法點擊
  18. pop.setFocusable(true);
  19. btn.setOnClickListener(new OnClickListener() {
  20. @Override
  21. public void onClick(View v) {
  22. if(pop.isShowing()) {
  23. // 隱藏窗口,如果設置了點擊窗口外小時即不需要此方式隱藏
  24. pop.dismiss();
  25. } else {
  26. // 顯示窗口
  27. pop.showAsDropDown(v);
  28. }
  29. }
  30. });
  31. }
  32. }

main.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="fill_parent"
  4. android:layout_height="fill_parent"
  5. android:orientation="vertical" >
  6. <Button
  7. android:id="@+id/btn"
  8. android:layout_width="wrap_content"
  9. android:layout_height="wrap_content"
  10. android:text="dianji" />
  11. </LinearLayout>

main2.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="fill_parent"
  4. android:layout_height="fill_parent"
  5. android:orientation="vertical" >
  6. <Button
  7. android:id="@+id/a"
  8. android:layout_width="wrap_content"
  9. android:layout_height="wrap_content"
  10. android:text="AAAAA" />
  11. <Button
  12. android:layout_width="wrap_content"
  13. android:layout_height="wrap_content"
  14. android:text="BBBBB" />
  15. <Button
  16. android:layout_width="wrap_content"
  17. android:layout_height="wrap_content"
  18. android:text="CCCCC" />
  19. <Button
  20. android:layout_width="wrap_content"
  21. android:layout_height="wrap_content"
  22. android:text="DDDDD" />
  23. </LinearLayout>

效果很不錯~~~

更多Android相關信息見Android 專題頁面 http://www.linuxidc.com/topicnews.aspx?tid=11

Copyright © Linux教程網 All Rights Reserved