• Android学习笔记 79. 菜单和选择器


    Android学习笔记

    Android 开发者基础知识 (Java) —— Google Developers 培训团队

    第2单元 用户体验

    第4课 用户互动

    79. 菜单和选择器
    你会做什么
    • 继续从之前的实践中为 Droid Cafe 项目添加功能。
    • 将菜单项添加到选项菜单。
    • 为菜单项添加图标以显示在应用栏中。
    • 将菜单项单击连接到处理单击事件的事件处理程序。
    • 使用警报对话框来请求用户的选择。
    • 使用日期选择器进行日期输入。
    79.1 将项目添加到选项菜单
    1. 检查代码

      应用栏是显示屏顶部的一个部分,可以显示活动标题、导航和其他交互项。根据设备上运行的 Android 版本,本机的ActionBar行为会有所不同。因此,如果要添加选项菜单,则应使用 v7 appcompat支持库 Toolbar作为应用栏。使用 Toolbar可以轻松设置适用于最广泛设备的应用栏,并且还为您提供了稍后在应用开发时自定义应用栏的空间。Toolbar包括最新功能,适用于任何可以使用支持库的设备。

      在这里插入图片描述

    2. 在选项菜单中添加更多菜单项

      <menu 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"
          tools:context="com.example.android.droidcafeoptions.MainActivity">
          <item
              android:id="@+id/action_contact"
              android:orderInCategory="100"
              android:title="@string/action_contact"
              app:showAsAction="never" />
          <item
              android:id="@+id/action_order"
              android:icon="@drawable/ic_shopping_cart"
              android:orderInCategory="10"
              android:title="@string/action_order"
              app:showAsAction="always" />
          <item
              android:id="@+id/action_status"
              android:icon="@drawable/ic_status_info"
              android:orderInCategory="20"
              android:title="@string/action_status"
              app:showAsAction="always" />
          <item
              android:id="@+id/action_favorites"
              android:icon="@drawable/ic_favorite"
              android:orderInCategory="30"
              android:title="@string/action_favorites"
              app:showAsAction="ifRoom" />
      menu>
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
      • 27
      • 28
    79.2 为菜单项添加图标
    1. 为菜单项添加图标

    2. 将菜单项显示为应用栏中图标

      在这里插入图片描述

    79.3 处理选中的菜单项
    1. 创建显示菜单选项的方法

      public void displayToast(String message) {
         Toast.makeText(getApplicationContext(), message,
                                Toast.LENGTH_SHORT).show();
      }
      
      • 1
      • 2
      • 3
      • 4
    2. 使用 onOptionsItemSelected 事件处理程序

    3. 从菜单项启动 Activity

    完整项目代码:https://github.com/google-developer-training/android-fundamentals-apps-v2/tree/master/DroidCafeOptions

    79.4 使用对话框请求用户选择
    1. 创建一个新应用程序以显示对话框

      在这里插入图片描述

      布局文件

      
      <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">
      
          <TextView
              android:id="@+id/textView"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="@string/hello_world"
              app:layout_constraintBottom_toBottomOf="parent"
              app:layout_constraintLeft_toLeftOf="parent"
              app:layout_constraintRight_toRightOf="parent"
              app:layout_constraintTop_toTopOf="parent" />
      
          <Button
              android:id="@+id/button"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_marginEnd="8dp"
              android:layout_marginStart="8dp"
              android:layout_marginTop="8dp"
              android:onClick="onClickShowAlert"
              android:text="@string/alert_button"
              app:layout_constraintEnd_toEndOf="parent"
              app:layout_constraintStart_toStartOf="parent"
              app:layout_constraintTop_toBottomOf="@+id/textView" />
      
      androidx.constraintlayout.widget.ConstraintLayout>
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
      • 27
      • 28
      • 29
      • 30
      • 31
      • 32
    2. 添加对话框以及点击事件

      MainActivity.java

      package com.dingjiaxiong.dialogforalert;
      
      import androidx.appcompat.app.AlertDialog;
      import androidx.appcompat.app.AppCompatActivity;
      
      import android.content.DialogInterface;
      import android.os.Bundle;
      import android.view.View;
      import android.widget.Toast;
      
      public class MainActivity extends AppCompatActivity {
      
          /**
           * Creates the view.
           *
           * @param savedInstanceState Saved instance state bundle.
           */
          @Override
          protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
          }
      
          /**
           * Handles the Alert button click. Builds the alert dialog with a title,
           * message, and OK and Cancel buttons. Also defines Toast messages to appear
           * depending on which alert button is clicked, and shows the alert dialog.
           *
           * @param view  The view in which the alert will appear.
           */
          public void onClickShowAlert(View view) {
              AlertDialog.Builder myAlertBuilder =
                      new AlertDialog.Builder(MainActivity.this);
      
              // Set the dialog title and message.
              myAlertBuilder.setTitle(R.string.alert_title);
              myAlertBuilder.setMessage(R.string.alert_message);
      
              // Add the dialog buttons.
              myAlertBuilder.setPositiveButton(R.string.ok_button,
                      new DialogInterface.OnClickListener() {
                          public void onClick(DialogInterface dialog, int which) {
                              // User clicked OK button.
                              Toast.makeText(getApplicationContext(),
                                      R.string.pressed_ok,
                                      Toast.LENGTH_SHORT).show();
                          }
                      });
      
              myAlertBuilder.setNegativeButton(R.string.cancel_button,
                      new DialogInterface.OnClickListener() {
                          public void onClick(DialogInterface dialog, int which) {
                              // User cancelled the dialog.
                              Toast.makeText(getApplicationContext(),
                                      R.string.pressed_cancel,
                                      Toast.LENGTH_SHORT).show();
                          }
                      });
              // Create and show the AlertDialog.
              myAlertBuilder.show();
          }
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
      • 27
      • 28
      • 29
      • 30
      • 31
      • 32
      • 33
      • 34
      • 35
      • 36
      • 37
      • 38
      • 39
      • 40
      • 41
      • 42
      • 43
      • 44
      • 45
      • 46
      • 47
      • 48
      • 49
      • 50
      • 51
      • 52
      • 53
      • 54
      • 55
      • 56
      • 57
      • 58
      • 59
      • 60
      • 61
      • 62
    3. 运行

      在这里插入图片描述

    79.5 使用选择器进行用户输入

    Android 提供了现成的对话框,称为选择器,用于选择时间或日期。您可以使用它们来确保您的用户选择格式正确并调整为用户本地时间和日期的有效时间或日期。每个选择器都提供了用于选择时间(小时、分钟、上午/下午)或日期(月、日、年)的每个部分的控件。

    项目地址

    https://github.com/google-developer-training/android-fundamentals-apps-v2/tree/master/PickerForDate

    1. 创建一个新应用程序以显示日期选择器

      在这里插入图片描述

    2. 布局

      
      <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">
      
          <TextView
              android:id="@+id/textView"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="@string/hello_world"
              app:layout_constraintBottom_toBottomOf="parent"
              app:layout_constraintLeft_toLeftOf="parent"
              app:layout_constraintRight_toRightOf="parent"
              app:layout_constraintTop_toTopOf="parent" />
      
          <Button
              android:id="@+id/button"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_marginEnd="8dp"
              android:layout_marginStart="8dp"
              android:layout_marginTop="8dp"
              android:onClick="showDatePicker"
              android:text="@string/date_button"
              app:layout_constraintEnd_toEndOf="parent"
              app:layout_constraintStart_toStartOf="parent"
              app:layout_constraintTop_toBottomOf="@+id/textView" />
      
      androidx.constraintlayout.widget.ConstraintLayout>
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
      • 27
      • 28
      • 29
      • 30
      • 31
      • 32
    3. 日期选择器

      DatePickerFragment.java

      package com.dingjiaxiong.pickerfordate;
      
      import android.app.DatePickerDialog;
      import android.app.Dialog;
      import android.os.Bundle;
      import android.widget.DatePicker;
      
      import androidx.annotation.NonNull;
      import androidx.fragment.app.DialogFragment;
      
      import java.util.Calendar;
      
      public class DatePickerFragment extends DialogFragment
              implements DatePickerDialog.OnDateSetListener {
      
          /**
           * Creates the date picker dialog with the current date from Calendar.
           *
           * @param savedInstanceState    Saved instance state bundle
           * @return DatePickerDialog     The date picker dialog
           */
          @NonNull
          @Override
          public Dialog onCreateDialog(Bundle savedInstanceState) {
              // Use the current date as the default date in the picker.
              final Calendar c = Calendar.getInstance();
              int year = c.get(Calendar.YEAR);
              int month = c.get(Calendar.MONTH);
              int day = c.get(Calendar.DAY_OF_MONTH);
      
              // Create a new instance of DatePickerDialog and return it.
              return new DatePickerDialog(getActivity(), this, year, month, day);
          }
      
          /**
           * Grabs the date and passes it to processDatePickerResult().
           *
           * @param datePicker  The date picker view
           * @param year  The year chosen
           * @param month The month chosen
           * @param day   The day chosen
           */
          @Override
          public void onDateSet(DatePicker datePicker, int year, int month, int day) {
              // Set the activity to the Main Activity.
              MainActivity activity = (MainActivity) getActivity();
              // Invoke Main Activity's processDatePickerResult() method.
              activity.processDatePickerResult(year, month, day);
          }
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
      • 27
      • 28
      • 29
      • 30
      • 31
      • 32
      • 33
      • 34
      • 35
      • 36
      • 37
      • 38
      • 39
      • 40
      • 41
      • 42
      • 43
      • 44
      • 45
      • 46
      • 47
      • 48
      • 49
      • 50
    4. 主MainActivity

      package com.dingjiaxiong.pickerfordate;
      
      import androidx.appcompat.app.AppCompatActivity;
      import androidx.fragment.app.DialogFragment;
      
      import android.os.Bundle;
      import android.view.View;
      import android.widget.Toast;
      
      public class MainActivity extends AppCompatActivity {
      
          /**
           * Creates the view.
           * @param savedInstanceState Saved instance state bundle.
           */
          @Override
          protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
          }
      
          /**
           * Handles the button click to create a new date picker fragment and
           * show it.
           *
           * @param view View that was clicked
           */
          public void showDatePicker(View view) {
              DialogFragment newFragment = new DatePickerFragment();
              newFragment.show(getSupportFragmentManager(),
                      getString(R.string.datepicker));
          }
      
          /**
           * Process the date picker result into strings that can be displayed in
           * a Toast.
           *
           * @param year Chosen year
           * @param month Chosen month
           * @param day Chosen day
           */
          public void processDatePickerResult(int year, int month, int day) {
              String month_string = Integer.toString(month + 1);
              String day_string = Integer.toString(day);
              String year_string = Integer.toString(year);
              String dateMessage = (month_string +
                      "/" + day_string +
                      "/" + year_string);
      
              Toast.makeText(this, getString(R.string.date) + dateMessage,
                      Toast.LENGTH_SHORT).show();
          }
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
      • 27
      • 28
      • 29
      • 30
      • 31
      • 32
      • 33
      • 34
      • 35
      • 36
      • 37
      • 38
      • 39
      • 40
      • 41
      • 42
      • 43
      • 44
      • 45
      • 46
      • 47
      • 48
      • 49
      • 50
      • 51
      • 52
      • 53
    5. 运行

      在这里插入图片描述

    79.6 小结

    提供选项菜单和应用栏:

    • 启动您的应用程序或Activity使用基本活动模板来自动设置应用程序栏、选项菜单和浮动操作按钮。
    • 该模板设置 CoordinatorLayout具有嵌入式 布局的AppBarLayout布局。AppBarLayout就像一个垂直的LinearLayout。它使用 Toolbar支持库中的类而不是 nativeActionBar来实现应用栏。
    • 模板修改AndroidManifest.xml文件以便.MainActivity Activity设置为使用NoActionBar主题。这个主题在styles.xml文件中定义。
    • 模板设置MainActivity为扩展AppCompatActivity并以方法开始,该onCreate()方法设置内容视图和Toolbar. 然后它调用 setSupportActionBar()并传递toolbar给它,将 设置toolbarActivity.
    • menu_main.xml在文件中定义菜单项。该android:orderInCategory属性指定菜单项在菜单中出现的顺序,最小的数字在菜单中出现在较高的位置。
    • 使用该 onOptionsItemSelected()方法确定点击了哪个菜单项。

    为选项菜单项添加图标:

    • Project > Android窗格中展开res,然后右键单击(或 Control-单击)drawable文件夹。选择新建 > 图像资源
    • 在下拉菜单中选择操作栏和选项卡项,然后更改图像文件的名称。
    • 单击剪贴画图像以选择剪贴画图像作为图标。选择一个图标。
    • 主题下拉菜单中选择HOLO_DARK 。

    在应用栏中将菜单项显示为图标:

    • 使用具有以下值的app:showAsAction属性。menu_main.xml
    • "always":始终出现在应用栏中。(如果没有足够的空间,它可能会与其他菜单图标重叠。)
    • "ifRoom":如果有空间,会出现在应用栏中。
    • "never":从不出现在应用栏中;它的文本出现在溢出菜单中。

    使用警告对话框:

    • 使用对话框来请求用户的选择,例如要求用户点击OKCancel的警报。谨慎使用对话框,因为它们会中断用户的工作流程。
    • 使用该类的 AlertDialogDialog类来显示警报的标准对话框。
    • 用于 AlertDialog.Builder构建标准警报对话框, setTitle()用于设置其标题、 setMessage()设置其消息和 setPositiveButton()设置 setNegativeButton()其按钮。

    使用选择器进行用户输入:

    • 使用 DialogFragment, 的子类 Fragment来构建选择器,例如日期选择器或时间选择器。
    • 创建一个DialogFragment, 并实现 DatePickerDialog.OnDateSetListener创建一个带有监听器的标准日期选择器。包括 onDateSet()在这个Fragment.
    • onCreateView()方法 替换为onCreateDialog()返回Dialog。从 初始化日期选择器的日期 Calendar,并将对话框和这些值返回给Activity
    • 创建一个 用于管理和显示日期选择器FragmentManager的 实例。getSupportFragmentManager()``Fragment
  • 相关阅读:
    rtc的计时方式
    asp.net+sqlserver+c#学生作品展示及评分系统
    Ai作图可控性演进——从SD到MJ
    mysql日期月份相关函数
    Python NumPy 基础:数组和向量计算
    学习总结1
    SpringMVC学习案例2:
    45、tomcat+课后实验
    uniapp webview实现双向通信
    PMBOK知识点整理【第四章项目整合管理】(49个子过程、输入、工具和技术、输出)
  • 原文地址:https://blog.csdn.net/weixin_44226181/article/details/126398865