iT邦幫忙

2024 iThome 鐵人賽

DAY 18
0

接上半部已經介紹過的6種Dialog,不明白或需要的可以翻翻上一篇~
我們繼續下半部剩下的Dialog,這篇學完就能靈活運用Dialog。


7.單選的對話框

// 單選對話框
        singlechoiceButton = findViewById(R.id.main_singleChoice_btn);
        singlechoiceButton.setOnClickListener((v) -> {
            int choice = 0; //預設選擇 選項1
            String[] items = {"選擇1", "選擇2", "選擇3", "選擇4","選擇5"};
            AlertDialog.Builder dialog = new AlertDialog.Builder(this);

            // 前面第一個參數:設置選項List
            // 後面第二個參數: 設置預設選中項(選項1)
            dialog.setSingleChoiceItems(items, choice, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    int choice = i;
                }
            });
            dialog.setPositiveButton("確定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    Toast.makeText(context, "你選擇" + items[choice], Toast.LENGTH_SHORT).show();
                }
            });
            dialog.show(); // 顯示dialog
        });
  • 執行畫面
    https://ithelp.ithome.com.tw/upload/images/20240926/20168454c3WlEq9X1P.png
    (按下確認)
    https://ithelp.ithome.com.tw/upload/images/20240926/20168454yWplkhOGwY.png

8.複選的對話框

//複選對話框
        checkButton = findViewById(R.id.main_check_btn);
        checkButton.setOnClickListener((v) -> {
            String[] items = {"東西1", "東西2", "東西3", "東西4","東西5"};
            // 設置默認選中項, false表示未選中, true表示選中(我默認第三個為以選擇狀態)
            boolean choice[] = {false,  false, true, false, false};
            AlertDialog.Builder dialog = new AlertDialog.Builder(this);
            dialog.setTitle("標題內文");
            dialog.setMultiChoiceItems(items, choice,
                    new DialogInterface.OnMultiChoiceClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i, boolean bol) {
                            choice[i] = bol;
                        }
                    }
            );

            dialog.setPositiveButton("確定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    String result = "";
                    for (int j = 0; j < items.length; j++) {
                        if (choice[j]) {
                            result += items[j] + "  ";
                        }
                    }
                    Toast.makeText(context, "你選擇" + result, Toast.LENGTH_SHORT).show();
                }
            });
            dialog.show(); // 顯示dialog
        });
  • 執行畫面
    https://ithelp.ithome.com.tw/upload/images/20240926/20168454u8aqDLUnhC.png
    (複選好後,按下確認)
    https://ithelp.ithome.com.tw/upload/images/20240926/20168454ynMcBDTd9i.png

9.進度條的對話框

//進度條對話框
        progressbarButton = findViewById(R.id.main_progressbar_btn);
        progressbarButton.setOnClickListener((v) -> {
            ProgressDialog dialog = new ProgressDialog(this);
            dialog.setMessage("載入中...");
            //關閉
            dialog.setCancelable(false);
            //設置進度條樣式 - 水平
            dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            dialog.setMax(100); // 設定進度條最大值

            // 模擬進度條跑動
            progressValue = 0;
            Timer timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    progressValue += new Random().nextInt(15);
                    dialog.setProgress(progressValue);
                    if (progressValue > 100) {
                        timer.cancel();
                        dialog.dismiss(); //關閉對話框
                    }
                }
            },0,200);
            dialog.show();
        });
  • 執行畫面
    https://ithelp.ithome.com.tw/upload/images/20240926/20168454ao9sbTj9bX.png
    (數值要跑過100時會關閉對話框)

10.等待條的對話框

//等待型對話框
        waitButton = findViewById(R.id.main_wait_btn);
        waitButton.setOnClickListener((v) -> {
            ProgressDialog dialog = new ProgressDialog(this);
            dialog.setTitle("進度");
            dialog.setMessage("等待中...");
            dialog.show();
        });
  • 執行畫面
    https://ithelp.ithome.com.tw/upload/images/20240926/20168454TnBQAPttCh.png

AlertDialog

  • .xml 介面
    https://ithelp.ithome.com.tw/upload/images/20240926/20168454IYyiPnnjdE.png
    (完整程式碼)
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.3" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.7" />


    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.55" />


    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.45" />

    <Button
        android:id="@+id/main_AlertDialog_btn"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:text="點擊開啟AlertDialog"
        app:layout_constraintBottom_toTopOf="@+id/guideline5"
        app:layout_constraintEnd_toStartOf="@+id/guideline4"
        app:layout_constraintStart_toStartOf="@+id/guideline"
        app:layout_constraintTop_toTopOf="@+id/guideline2" />

</androidx.constraintlayout.widget.ConstraintLayout>
  • 這次新增兩種.xml檔

  • 在layout,移到New點擊Layout Resource File,命名好點擊OK
    https://ithelp.ithome.com.tw/upload/images/20240926/20168454RtORfFKKLZ.png

  • 在drawable,移到New點擊Drawable Resource File,命名好點擊OK
    https://ithelp.ithome.com.tw/upload/images/20240926/201684549EnFHWOE6s.png

  • 新增完後的畫面
    https://ithelp.ithome.com.tw/upload/images/20240926/20168454l9xsfCxjNj.png

  • dialog.shape.xml
    https://ithelp.ithome.com.tw/upload/images/20240926/20168454c0XWX0xLmw.png
    右邊可以看到目前設定的樣式預覽狀態

(完整程式碼)

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle"
    >
    <!-- 圓角幅度 -->
    <corners
        android:radius="15dip"
        />

    <!-- 底部顏色 -->
    <solid
        android:color="@android:color/black"
        />

    <!--框線-->
    <stroke
        android:width="1dip"
        android:color="#22738B"
        />

    <!-- 顏色漸層 -->
    <gradient
        android:startColor="#71A4D7"
        android:endColor="#9471F5"
        android:angle="315"
        />

    <!-- 尺寸大小-->
    <size
        android:width="150dip"
        android:height="120dip"
        />

</shape>
  • dialog_item.xml
  • 呈現樣子
    https://ithelp.ithome.com.tw/upload/images/20240926/20168454ZiuXPE172Y.png

(完整程式碼)

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/dialog_shape">


    <TextView
        android:id="@+id/dialog_title_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="8dp"
        android:text="標題文字"
        android:textSize="25dp"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        android:textStyle="bold"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />


    <TextView
        android:id="@+id/dialog_menu_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="72dp"
        android:text="內容文字"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        android:textSize="20dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.528"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/dialog_title_tv" />

    <Button
        android:id="@+id/dialog_dia_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="64dp"
        android:layout_marginEnd="16dp"
        android:layout_marginBottom="8dp"
        android:background="@android:color/transparent"
        android:text="OK"
        android:textColor="#023F4F"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/dialog_menu_tv"
        app:layout_constraintVertical_bias="0.0" />
</androidx.constraintlayout.widget.ConstraintLayout>
  • MainActivity
public class MainActivity extends AppCompatActivity {
    //宣告
    private Button AlertDialogButton;
    private Button diaButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //綁定
        AlertDialogButton = findViewById(R.id.main_AlertDialog_btn);

        //AlertDialog Button監聽器
        AlertDialogButton.setOnClickListener((v)->{
            //創建AlertDialog.Builder
            AlertDialog.Builder mBuilder = new AlertDialog.Builder(this);

            //嵌入View
            View view = getLayoutInflater().inflate(R.layout.dialog_item,null);

            //連結關閉視窗的Button
            diaButton = view.findViewById(R.id.dialog_dia_btn);

            //設置View
            mBuilder.setView(view);
            AlertDialog dialog = mBuilder.create();
            diaButton.setOnClickListener(v1 -> {dialog.dismiss();});
            dialog.show();

            //取得螢幕解析度
            DisplayMetrics dm = new DisplayMetrics();

            //取得螢幕寬度值
            getWindowManager().getDefaultDisplay().getMetrics(dm);

            //設置螢幕寬度值
            dialog.getWindow().setLayout(dm.widthPixels-230, ViewGroup.LayoutParams.WRAP_CONTENT);

            //將原本的AlertDialog的背景設為透明
            dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        });

    }
}
  • 執行畫面
    (未點擊按鈕)
    https://ithelp.ithome.com.tw/upload/images/20240926/20168454Qpt5O2sAbG.png
    (點擊按鈕後)
    https://ithelp.ithome.com.tw/upload/images/20240926/20168454OtFXpMyy9k.png

Dialog告一段落。
恭喜你成功又學會了一個元件Dialog~ 又邁向成功路上的一步呢! (慢慢溫水煮青蛙的痛苦ಥ_ಥ


上一篇
元件篇-Dialog(上) Day17
下一篇
元件篇-RecyclerView Day19
系列文
Android 元件總動員 - 運用與實踐元件指南30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言