目錄
Android ProgressDialog (進度條對話框)
例子
Android DatePickerDialog 日期選擇對話框
例子
Android TimePickerDialog 時間選擇對話框
Android PopupWindow 懸浮框
構造函數
方法
例子
官方文檔
Android OptionMenu 選項菜單
例子
官方文檔
Android ProgressDialog (進度條對話框)
Android ProgressDialog 已經在 API 26+ 中被廢棄,ProgressDialog 不能直接從 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"xmlns:tools="http://schemas.android.com/tools"android:orientation="vertical"android:gravity="center"tools:context=".MainActivity"><Buttonandroid:id="@+id/btn_show_normal_progress_dialog"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="顯示普通ProgressDialog" /><Buttonandroid:id="@+id/btn_show_indeterminate_progress_dialog"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="顯示不確定結束的ProgressDialog" /><Buttonandroid:id="@+id/btn_show_determinate_progress_dialog"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="顯示確定結束的ProgressDialog" /></LinearLayout>
package com.example.myapplication;import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;import androidx.appcompat.app.AppCompatActivity;public class MainActivity extends AppCompatActivity {private ProgressDialog progressDialog;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Button btnShowNormal = findViewById(R.id.btn_show_normal_progress_dialog);Button btnShowIndeterminate = findViewById(R.id.btn_show_indeterminate_progress_dialog);Button btnShowDeterminate = findViewById(R.id.btn_show_determinate_progress_dialog);btnShowNormal.setOnClickListener(v -> {showProgressDialog(ProgressDialog.STYLE_SPINNER); // 普通ProgressDialog});btnShowIndeterminate.setOnClickListener(v -> {showProgressDialog(ProgressDialog.STYLE_HORIZONTAL); // 不確定結束的ProgressDialog});btnShowDeterminate.setOnClickListener(v -> {showDeterminateProgressDialog(); // 確定結束的ProgressDialog});}private void showProgressDialog(int style) {progressDialog = new ProgressDialog(MainActivity.this);progressDialog.setTitle("軟件更新中");progressDialog.setMessage("軟件正在更新中,請稍后...");progressDialog.setProgressStyle(style);progressDialog.setCancelable(false); // 防止用戶取消progressDialog.show();// 模擬操作new Handler().postDelayed(() -> {progressDialog.dismiss();}, 3000); // 模擬3秒后關閉對話框}private void showDeterminateProgressDialog() {progressDialog = new ProgressDialog(MainActivity.this);progressDialog.setTitle("軟件更新中");progressDialog.setMessage("軟件正在更新中,請稍后...");progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);progressDialog.setMax(100); // 設置最大值progressDialog.setCancelable(false);progressDialog.show();// 模擬下載進度更新new Thread(() -> {int progress = 0;while (progress <= 100) {progressDialog.setProgress(progress);progress += 10;try {Thread.sleep(500); // 模擬下載延遲} catch (InterruptedException e) {e.printStackTrace();}}progressDialog.dismiss();}).start();}
}
Android DatePickerDialog 日期選擇對話框
當用戶點擊一個按鈕,彈出日期選擇對話框是一個常見的需求。
例子
<?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"xmlns:tools="http://schemas.android.com/tools"android:orientation="vertical"android:gravity="center"tools:context=".MainActivity"><Buttonandroid:id="@+id/btn_pick_date"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="選擇日期"/></LinearLayout>
package com.example.myapplication;import android.app.DatePickerDialog;
import android.os.Bundle;
import android.widget.Button;import androidx.appcompat.app.AppCompatActivity;import java.util.Calendar;public class MainActivity extends AppCompatActivity {private Button btnPickDate;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);btnPickDate = findViewById(R.id.btn_pick_date);btnPickDate.setOnClickListener(v -> showDatePickerDialog());}private void showDatePickerDialog() {// 獲取當前日期Calendar calendar = Calendar.getInstance();int year = calendar.get(Calendar.YEAR);int month = calendar.get(Calendar.MONTH);int day = calendar.get(Calendar.DAY_OF_MONTH);// 創建并顯示日期選擇對話框DatePickerDialog datePickerDialog = new DatePickerDialog(this, (view, selectedYear, selectedMonth, selectedDay) -> {// 處理選擇的日期String selectedDate = selectedYear + "-" + (selectedMonth + 1) + "-" + selectedDay;btnPickDate.setText(selectedDate); // 在按鈕上顯示選擇的日期}, year, month, day);datePickerDialog.show();}
}
Android TimePickerDialog 時間選擇對話框
Android TimePickerDialog ( 時間選擇對話框 ) 會彈出一個對話框形式的時間選擇器。
<?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"xmlns:tools="http://schemas.android.com/tools"android:orientation="vertical"android:gravity="center"tools:context=".MainActivity"><Buttonandroid:id="@+id/btn_pick_time"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="選擇時間"/></LinearLayout>
package com.example.myapplication;import android.app.TimePickerDialog;
import android.os.Bundle;
import android.widget.Button;import androidx.appcompat.app.AppCompatActivity;import java.util.Calendar;
import java.util.TimeZone;public class MainActivity extends AppCompatActivity {private Button btnPickTime;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);btnPickTime = findViewById(R.id.btn_pick_time);btnPickTime.setOnClickListener(v -> showTimePickerDialog());}private void showTimePickerDialog() {// 獲取中國的當前時間Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT+08:00")); // 設置時區為中國標準時間int hour = calendar.get(Calendar.HOUR_OF_DAY);int minute = calendar.get(Calendar.MINUTE);// 創建并顯示時間選擇對話框TimePickerDialog timePickerDialog = new TimePickerDialog(this, (view, selectedHour, selectedMinute) -> {// 處理選擇的時間String selectedTime = String.format("%02d:%02d", selectedHour, selectedMinute);btnPickTime.setText(selectedTime); // 在按鈕上顯示選擇的時間}, hour, minute, true); // 最后一個參數表示是否為24小時制timePickerDialog.show();}
}
Android PopupWindow 懸浮框
PopupWindow 是一個彈出窗口控件,可以顯示任意 View,并且浮動在當前 Activity 的頂部。通常用于懸浮在其他 UI 控件旁邊,提供額外的信息或操作選項。與 AlertDialog 不同,PopupWindow 的位置可以自由設置,可以根據需要顯示在屏幕的任何位置。
構造函數
PopupWindow 類的構造函數如下:
- PopupWindow(): 創建一個空的 PopupWindow 對象。
- PopupWindow(Context context): 使用指定的上下文創建 PopupWindow 對象。
- PopupWindow(Context context, AttributeSet attrs): 使用指定的上下文和屬性集創建 PopupWindow 對象。
- PopupWindow(Context context, AttributeSet attrs, int defStyleAttr): 使用指定的上下文、屬性集和樣式資源創建 PopupWindow 對象。
- PopupWindow(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes): 使用指定的上下文、屬性集、樣式資源和主題資源創建 PopupWindow 對象。
- PopupWindow(View contentView): 使用指定的內容視圖創建 PopupWindow 對象。
- PopupWindow(int width, int height): 創建指定寬高的 PopupWindow 對象。
- PopupWindow(View contentView, int width, int height): 使用指定的內容視圖以及寬高創建 PopupWindow 對象。
- PopupWindow(View contentView, int width, int height, boolean focusable): 使用指定的內容視圖、寬高和焦點設置創建 PopupWindow 對象。
方法
以下是一些重要的 PopupWindow 方法的說明:
- setContentView(View contentView): 設置 PopupWindow 顯示的 View。
- getContentView(): 獲取 PopupWindow 顯示的 View。
- showAsDropDown(View anchor): 在指定控件正下方顯示 PopupWindow,無偏移。
- showAsDropDown(View anchor, int xoff, int yoff): 在指定控件位置顯示 PopupWindow,并可以設置偏移量。
- showAtLocation(View parent, int gravity, int x, int y): 在父控件指定位置顯示 PopupWindow,可以設置具體位置、偏移量等。需要傳入 Activity 中的任意一個 View 作為 parent 參數。
- setWidth(int width) / setHeight(int height): 設置 PopupWindow 的寬度和高度,也可以在構造方法中指定。
- setFocusable(true): 設置 PopupWindow 是否具有焦點。當設置為 true 時,PopupWindow 彈出后會處理觸摸事件和物理按鍵事件,必須先讓 PopupWindow 消失才能響應其他事件。
- setAnimationStyle(int style): 設置 PopupWindow 彈出和消失的動畫效果。
例子
1、創建 res/layout/popup_content.xml 布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="wrap_content"android:layout_height="wrap_content"android:orientation="vertical"android:padding="16dp"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="彈出內容"android:textSize="16sp"android:textColor="@android:color/black" /><Buttonandroid:id="@+id/close_button"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="關閉"android:textColor="@android:color/white"android:background="@color/purple" />
</LinearLayout>
2、修改 res/layout/activity_main.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"xmlns:tools="http://schemas.android.com/tools"android:orientation="vertical"android:gravity="center"tools:context=".MainActivity"><Buttonandroid:id="@+id/show_popup_button"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="顯示彈出菜單" /></LinearLayout>
3、修改 MainActivity.java:
package com.example.myapplication;import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.PopupWindow;import androidx.appcompat.app.AppCompatActivity;public class MainActivity extends AppCompatActivity {private PopupWindow popupWindow;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);// 創建一個 View 作為 PopupWindow 的內容視圖View contentView = LayoutInflater.from(this).inflate(R.layout.popup_content, null);// 創建 PopupWindow 對象并設置內容視圖、寬高popupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);// 設置焦點,讓 PopupWindow 彈出后處理觸摸事件和物理按鍵事件popupWindow.setFocusable(true);// 找到觸發彈出 PopupWindow 的按鈕Button showPopupButton = findViewById(R.id.show_popup_button);showPopupButton.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {// 在按鈕下方顯示 PopupWindow,無偏移popupWindow.showAsDropDown(v);}});// 找到關閉 PopupWindow 的按鈕Button closeButton = contentView.findViewById(R.id.close_button);closeButton.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {// 關閉 PopupWindowpopupWindow.dismiss();}});}
}
官方文檔
-
Android PopupWindow
Android OptionMenu 選項菜單
在Android中,OptionMenu(選項菜單)的創建和管理不是通過XML直接實例化或某個類的實例化方法實現的,而是通過Activity提供的幾個生命周期方法進行動態創建和控制。
具體來說:
- onCreateOptionsMenu(Menu menu):這是用于初始化選項菜單的方法,在這個方法里,我們可以調用getMenuInflater().inflate(R.menu.menu_main, menu);來加載預定義在XML文件中的菜單項,或者通過調用menu對象的add()方法動態添加菜單項。
- onOptionsItemSelected(MenuItem item):當用戶點擊選項菜單中的某一項時,系統會調用此方法,我們可以在其中根據item的id進行相應的操作處理。
- onPrepareOptionsMenu(Menu menu):在每次菜單即將顯示前,系統都會調用此方法,以便我們可以根據當前應用的狀態動態修改菜單項的狀態或可見性等屬性。
- onOptionsMenuClosed(Menu menu):當選項菜單關閉后,系統會調用此回調方法,可以在此處執行菜單關閉后的清理工作。
- onMenuOpened(int featureId, Menu menu):如果我們的應用支持舊版的API(如ActionBar的子菜單),當選項菜單打開時,系統可能會調用此方法通知我們菜單已打開。
例子
1、在 res/menu/menu_main.xml 菜單文件中定義要顯示的菜單項:
<!-- menu_main.xml -->
<menu xmlns:android="http://schemas.android.com/apk/res/android"><itemandroid:id="@+id/menu_item1"android:title="選項 1" /><itemandroid:id="@+id/menu_item2"android:title="選項 2" />
</menu>
2、修改 res/layout/activity_main.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"xmlns:tools="http://schemas.android.com/tools"android:orientation="vertical"android:gravity="center"tools:context=".MainActivity"><Buttonandroid:id="@+id/open_popup_menu_button"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="顯示彈出菜單" /></LinearLayout>
3、修改 MainActivity.java:
package com.example.myapplication;import android.os.Bundle;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.PopupMenu;
import android.widget.Toast;import androidx.appcompat.app.AppCompatActivity;public class MainActivity extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Button openPopupMenuButton = findViewById(R.id.open_popup_menu_button);openPopupMenuButton.setOnClickListener(v -> {PopupMenu popupMenu = new PopupMenu(MainActivity.this, openPopupMenuButton);popupMenu.getMenuInflater().inflate(R.menu.menu_main, popupMenu.getMenu());popupMenu.setOnMenuItemClickListener(item -> {int id = item.getItemId();if (id == R.id.menu_item1) {// 處理選中 選項 1 的事件Toast.makeText(MainActivity.this, "選擇了選項1", Toast.LENGTH_SHORT).show();return true;} else if (id == R.id.menu_item2) {// 處理選中 選項 2 的事件Toast.makeText(MainActivity.this, "選擇了選項2", Toast.LENGTH_SHORT).show();return true;}return false;});popupMenu.show();});}
}
官方文檔
- Android menus
?