• android11——Material Design


    最佳的UI体验——Material Design

    Material is a design system created by Google to help teams build high-quality digital experiences for Android, iOS, Flutter, and the web.
    

    Toolbar

    • 颜色设置(values/themes中)

    • 修改style的ActionBar变为NoActionBar:

          <!-- Base application theme. -->
          <style name="Theme.MaterialTest" parent="Theme.MaterialComponents.DayNight.NoActionBar">
              <!-- Primary brand color. -->
              <item name="colorPrimary">@color/purple_500</item>
              <item name="colorPrimaryVariant">@color/purple_700</item>
              <item name="colorOnPrimary">@color/white</item>
              <!-- Secondary brand color. -->
              <item name="colorSecondary">@color/teal_200</item>
              <item name="colorSecondaryVariant">@color/teal_700</item>
              <item name="colorOnSecondary">@color/black</item>
              <!-- Status bar color. -->
              <item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
              <!-- Customize your theme here. -->
      
          </style>
      
    • 当隐藏了ActionBar之后,在activity_main.xml中用Toolbar代替:

      <?xml version="1.0" encoding="utf-8"?>
      <FrameLayout 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.appcompat.widget.Toolbar
                  android:id="@+id/toolbar"
                  android:layout_width="match_parent"
                  android:layout_height="?attr/actionBarSize"
                  android:background="@color/design_default_color_primary"
                  android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
                  app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
                  />
      </FrameLayout>
      

      关于FrameLayout的命名空间含义:

      • xmlns:android指定了命名空间,从而可以使用android:id等写法。
      • xmlns:app则可以使用app:attribuite写法,而这个命名空间是新系统新增的,所以为了兼容老系统,就使用了app:attribute新写法。
      • app:popupTheme单独指定了弹出菜单项的颜色为浅色主题。
    • 给manifest添加android:label用于指定Toolbar中显示的文字内容:

          <application
              android:allowBackup="true"
              android:icon="@mipmap/ic_launcher"
              android:label="@string/app_name"
              android:roundIcon="@mipmap/ic_launcher_round"
              android:supportsRtl="true"
              android:theme="@style/Theme.MaterialTest">
              <activity
                  android:name=".MainActivity"
                  android:label="Fruits">
      
    • 在完成了布局后,最后,在mainactivity中设置:

          @Override
          protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
              // 下面这个步骤必须有,不然还是设置的是android.widget.Toolbar =>
              // manifest的activity中的android:label="Fruits"不会显示
              // 而我们这个地方导入的Toolbar则是androidx.appcompat.widget.Toolbar;
              Toolbar toolbar =(Toolbar) findViewById(R.id.toolbar);
              setSupportActionBar(toolbar);
          }
      
    • 给Toolbar添加action按钮:

      • 创建一个menu资源文件夹

    • 在menu文件夹中创建一个toolbar.xml,具体 代码如下:

      <?xml version="1.0" encoding="utf-8"?>
      <menu xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:app="http://schemas.android.com/apk/res-auto">
          <item
              android:id="@+id/backup"
              android:icon="@drawable/ic_backup"
              android:title="Backup"
              app:showAsAction="always"/>
      
          <item
              android:id="@+id/delete"
              android:icon="@drawable/ic_delete"
              android:title="Delete"
              app:showAsAction="ifRoom"/>
      
          <item
              android:title="Settings"
              android:id="@+id/settings"
              android:icon="@drawable/ic_settings"
              app:showAsAction="never" />
      
      </menu>
      <!--
          android:id指定按钮id
          android:icon指定图标
          android:title指定按钮文字
          app:showAsAction用来指定按钮的位置,app为了兼容
              always:表示永远显示在Toolbar中
              ifRoom:表示如果屏幕空间足够显示
              never:表示永远显示在菜单栏。
      -->
      
    • 剩下的就和第二节activity中学习MENU一样,创建,显示,重写menu类方法:

      • onCreateOptionsMenu给当前activity创建menu
      • onOptionsItemSelected用于相应事件。
    • 【关于BUG】:只有上面的设置才能使用Toolbar,否则直接使用Toolbar会出现错误:

      java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme...
      

    滑动菜单

    所谓滑动菜单就是将一些菜单选项隐藏起来,而不是放置在主屏幕上,然后可以通过滑动的方式将菜单显示出来。

    DrawerLayout

    google提供的DrawerLayout控件可以用来实现滑动菜单。下面介绍他的用法:

    首先,他是一个布局,在布局中允许放入两个直接子控件:第一个子控件是主屏幕中显示的内容,第二个子控件是滑动菜单中显示的内容。因此,在activity_main.xml中代码修改如下:

    <androidx.drawerlayout.widget.DrawerLayout
        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:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
            <FrameLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent">
                    <androidx.appcompat.widget.Toolbar
                        android:id="@+id/toolbar"
                        android:layout_width="match_parent"
                        android:layout_height="?attr/actionBarSize"
                        android:background="@color/design_default_color_primary"
                        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
                        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
                        />
            </FrameLayout>
            <TextView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_gravity="start"
                android:background="#fff"
                android:text="This is menu"
                android:textSize="30sp"/>
    </androidx.drawerlayout.widget.DrawerLayout>
    

    这个时候就可以做到,左边向右边滑动,而显示的效果了。但是为了提示用户,应该在menu中添加一个home【这个是android自带的,我们只需要设置home

    的图标】:

    private DrawerLayout mDrawerLayout;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            // 下面这个步骤必须有,不然还是设置的是android.widget.Toolbar =>
            // activity中的android:label="Fruits"不会显示
            Toolbar toolbar =(Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
    		
            mDrawerLayout =(DrawerLayout) findViewById(R.id.drawer_layout);
            // 获取actionBar 然后设置HOME显示,并设置显示的图标
            ActionBar actionBar = getSupportActionBar();
            if (actionBar !=null ){
                actionBar.setDisplayHomeAsUpEnabled(true);
                actionBar.setHomeAsUpIndicator(R.drawable.ic_menu);
            }
    
        }
    	@SuppressLint("NonConstantResourceId")
        @Override
        public boolean onOptionsItemSelected(@NonNull MenuItem item) {
            // ...
            // 注意必须是android.R.id.home不是R.id.home位置不一样!足够HOME就是上面的actionBar.setHomeAsUpIndicator(R.drawable.ic_menu);
                case android.R.id.home:
                    mDrawerLayout.openDrawer(GravityCompat.START);
                    break;
                default:
                    break;
    
            }
            return true;
        }
    
    

    实际上使用TextView显示滑动菜单栏非常丑,google提供了一个控件叫NavigationView。这个控件是Material库提供的。

    • 添加依赖

      implementation 'de.hdodenhof:circleimageview:3.1.0'
      implementation 'com.google.android.material:material:1.2.1'
      
    • 编写导航的header的布局:里面包括头像,个人email和个人姓名等。【注意设置header的高度为定值180dp】

      <?xml version="1.0" encoding="utf-8"?>
      <RelativeLayout
          xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="match_parent"
          android:layout_height="180dp"
          android:padding="10dp"
          android:background="@color/design_default_color_primary">
      <!--  这个是一个圆形化工具 -->
      <de.hdodenhof.circleimageview.CircleImageView
          android:id="@+id/icon_image"
          android:layout_width="70dp"
          android:layout_height="70dp"
          android:src="@drawable/nav_icon"
          android:layout_centerInParent="true"/>
          <TextView
              android:id="@+id/mail_text"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_alignParentBottom="true"
              android:text="504084637@qq.com"
              android:textColor="#fff"
              android:textSize="14sp"/>
          <TextView
              android:id="@+id/user_text"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_above="@id/mail_text"
              android:text="Ssozh"
              android:textColor="#fff"
              android:textSize="14sp"/>
      </RelativeLayout>
      
    • 编写navigation的menu:nav_menu.xml,其中group的属性表示下面的item只能单选。

      <?xml version="1.0" encoding="utf-8"?>
      <menu xmlns:android="http://schemas.android.com/apk/res/android">
      <group android:checkableBehavior="single">
          <item
              android:id="@+id/nav_call"
              android:icon="@drawable/nav_call"
              android:title="Call" />
      
          <item
              android:id="@+id/nav_friends"
              android:icon="@drawable/nav_friends"
              android:title="Friends"/>
          <item
              android:id="@+id/nav_location"
              android:icon="@drawable/nav_location"
              android:title="Location"/>
      
          <item
              android:id="@+id/nav_task"
              android:icon="@drawable/nav_task"
              android:title="Tasks"/>
      </group>
      </menu>
      
    • 上面的布局(layout)和menu通过NavigationView将两个部分组合(放入DrawerLayout):

              <com.google.android.material.navigation.NavigationView
                  android:id="@+id/nav_view"
                  android:layout_width="match_parent"
                  android:layout_height="match_parent"
                  android:layout_gravity="start"
                  app:menu="@menu/nav_menu"
                  app:headerLayout="@layout/nav_header"/>
      
    • 虽然NavigationView虽然定义完成了,但还要处理菜单栏单选的点击事件。修改MainActivity的代码:

      NavigationView navView =(NavigationView) findViewById(R.id.nav_view);
      // nav_call表示默认选中。后面点击那个选中保持哪个
      navView.setCheckedItem(R.id.nav_call);
      navView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
          @Override
          public boolean onNavigationItemSelected(@NonNull MenuItem item) {
              mDrawerLayout.closeDrawers(); // 关闭全部的Drawers
              return true;
          }
      });
      

    悬浮按钮和可交互提示

    立面设计是material Design中一条非常重要的设计思想。在官方给出的示例中,最简单那且最具代表性的立面设计就是悬浮按钮了。

    FloatingActionButton

    floatingactionButton是material库中提供的一个控件,这个控件可以帮助我们轻松的实现悬浮按钮的效果。

    首先放置一张图片,然后修改activity_main.xml的代码:

                    <com.google.android.material.floatingactionbutton.FloatingActionButton
                            android:id="@+id/fab"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_gravity="bottom|end"
                            android:layout_margin="16dp"
                            android:src="@drawable/ic_done"
                            app:elevation="8dp"/>
    

    其中app:elevation="8dp"表示悬浮高度。响应事件和button没有任何区别~:

            FloatingActionButton fab  =(FloatingActionButton) findViewById(R.id.fab);
            // 注意这个的响应还是View的,不是NavigationView这样的~
            fab.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(MainActivity.this,"FAB clicked",Toast.LENGTH_SHORT).show();
                }
            });
    

    Snackbar

    material库提供更加先进的提示工具——snackbar。其实snackbar不是toast的代替品,他们有不同的应用场景。Toast的作用是告诉用户发生了什么事情。而snackbar则在这方面进行了扩展,它允许在提示中加入了一个可交互按钮。

    snackbar的用法也很简单,它和toast是基本相似的,修改MainActivity中的代码如下:

            FloatingActionButton fab  =(FloatingActionButton) findViewById(R.id.fab);
            // 注意这个的响应还是View的,不是NavigationView这样的~
            fab.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Snackbar.make(v,"Data deleted",Snackbar.LENGTH_SHORT)
                            .setAction("Undo", view -> {
                                Toast.makeText(MainActivity.this,"FAB clicked",Toast.LENGTH_SHORT).show();
                            });
                }
            });
    

    注意其中的lambda表达式,其实就是new View.OnClickListener(){}。上面代码可以看出来:

    • make()方法:来创建一个snackbar对象。
      • 第一个参数是当前界面的任意一个View都可以,
      • 第二个参数是snackbar要显示的内容。
      • 第三个参数是显示时长
    • .setAction()方法:用来设置一个动作,从而让Snackbar不仅仅是一个提示。

    但是Snackbar会把悬浮按钮挡住,这个只需要借助CoordinatorLayout就可以解决~

    CoordinatorLayout

    CoordinatorLayout可以说是一个加强版的FrameLayout,由androidX库提供。

    CoordinatorLayout可以监听其所有子控件的各种事件,并自动帮助我们做出最为合理的响应。

    所以直接CoordinatorLayout替代FrameLayout即可。

    卡片式布局

    卡片式布局也是materials design中提出的一个新概念,他可以让页面中的元素看起来就像在卡片中一样,并且还能拥有圆角和投影。

    MaterialCardView

    MaterialCardView是用于实现卡片式布局效果的重要控件。实际上,他也是一个frameLayout,只是额外提供了圆角和阴影等效果,看上去会有立体的感觉。

    • 添加依赖:

      implementation 'androidx.recyclerview:recyclerview:1.0.0'
      implementation 'com.github.bumptech.glide:glide:4.9.0'
      
    • 改写活动布局(activity_main)添加recyclerview:

                      <androidx.recyclerview.widget.RecyclerView
                          android:id="@+id/recycer_view"
                          android:layout_width="match_parent"
                          android:layout_height="match_parent"/>
      
    • 编写fruit_item布局:【这个地方使用了MaterialCardView包裹在最外层~】

      <?xml version="1.0" encoding="utf-8"?>
      <com.google.android.material.card.MaterialCardView
          xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="match_parent"
          android:layout_height="wrap_content">
      <LinearLayout
          android:orientation="vertical"
          android:layout_width="match_parent"
          android:layout_height="wrap_content">
          <ImageView
              android:id="@+id/fruit_image"
              android:layout_width="match_parent"
              android:layout_height="100dp"
              android:scaleType="centerCrop"/>
          <TextView
              android:id="@+id/fruit_name"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_gravity="center_horizontal"
              android:layout_margin="5dp"
              android:textSize="16sp"/>
      </LinearLayout>
      </com.google.android.material.card.MaterialCardView>
      
    • 定义实体类Fruit

      • int imageId
      • String fruitName
    • 定义适配器的类FruitAdapter包括:

      • FruitAdapter.ViewHolder内部类:用于设置fruit_item相关内容。

      • 重写onCreateViewHolder方法

      • 重写onBindViewHolder方法:

        @Override
        public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
            Fruit fruit = mFruitList.get(position);
            holder.fruitName.setText(fruit.getName());
            // 这个图片的绑定变了!
            Glide.with(mcontext).load(fruit.getImageId()).into(holder.fruitImage);
        }
        

        这个地方使用了Glide,他是用于对高清图像压缩防止内存溢出的设置图片方式。Glide.with()传入一个Context,Activity或Fragment参数,然后调用load()方法加载图片,加载可以是URL也可以是一个本地路径,或者是一个资源id,最后调用into()方法将图片设置到某一个具体的imageView中。

      • 重写getItemCount方法。

    • 最后修改MainActivity:

              // 关于materialCardView
              initFruits();
              RecyclerView recyclerView = (RecyclerView)findViewById(R.id.recycer_view);
              GridLayoutManager layoutManager = new GridLayoutManager(this,2);
              recyclerView.setLayoutManager(layoutManager);
              adapter = new FruitAdapter(fruitList);
              recyclerView.setAdapter(adapter);
          }
      
          private void initFruits() {
              fruitList.clear();
              for(int i=0;i<50;i++){
                  Random random = new Random();
                  int index = random.nextInt(fruits.length);
                  fruitList.add(fruits[index]);
              }
          }
      

    但是这个时候出现了问题:

    上面的ToolBar被遮挡了,所以需要使用AppBarLayout解决问题。

    AppBarLayout

    遮挡原因

    因为RecyclerView和Toolbar都放置在CoordinatorLayout中,额CoordinatorLayout就是一个加强版的FrameLayout,而FrameLayout中的所有控件在不进行明确定位的情况下,默认都会摆放在布局的左上角,从而产生了遮挡的现象。

    解决方法

    • 方法一:通过偏移,让recyclerview向下偏移一个Toolbar的高度,从而保证不被遮挡。

    • 方法二:使用appbarlayout:

      • 首先将toolbar嵌入到appbarlayout中
      • 然后给recyclerview指定一个布局行为:app:layout_behavior="@string/appbar_scrolling_view_behavior"
                      <com.google.android.material.appbar.AppBarLayout
                          android:layout_width="match_parent"
                          android:layout_height="wrap_content">
                              <androidx.appcompat.widget.Toolbar
                                  android:id="@+id/toolbar"
                                  android:layout_width="match_parent"
                                  android:layout_height="?attr/actionBarSize"
                                  android:background="@color/design_default_color_primary"
                                  android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
                                  app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
                                  />
                      </com.google.android.material.appbar.AppBarLayout>
      
                      <androidx.recyclerview.widget.RecyclerView
                          android:id="@+id/recycer_view"
                          android:layout_width="match_parent"
                          android:layout_height="match_parent"
                          app:layout_behavior="@string/appbar_scrolling_view_behavior"/>
      

    实际上,RecyclerView滚动的时候就已经将滚动事件通知给AppBarLayout了,只是我们还没进行处理而已。

    当appbarlayout接受到滚动事件的还是,它内部的子控件其实是可以指定如何去影响这些事件的,通过app:layout_scrollFlags属性就可以实现。

    在添加在toolbar中添加如下代码:

    scroll表示当recyclerview向上滚动的时候,toolbar会一起向上滚动,并实现隐藏。

    enterAlways表示当recyclerview向下滚动的时候,toolbar会跟着向下滚动并实现重新显示。

    snap表示当toolbar还没有完全隐藏或者显示的时候,会根据当前的滚动距离自动选择隐藏还是显示。

    app:layout_scrollFlags="scroll|enterAlways|snap"
    

    下拉刷新(不是上拉加载!)

    添加依赖:

    implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0'
    

    SwipeRefreshLayout就是用于实现下拉刷新功能的核心类,它是由androidX库提供的。我们把想要实现下拉刷新功能的控放置到swipeRefreshLayout中,就可以迅速让这个控件支持下拉刷新。那么在materialtext项目中,应该支持下拉刷新功能的控件自然就是recycleView了。

    • 首先在layout中添加swipeRefreshLayout

      在recyclerview的外面又嵌套了一层swipeRefreshLayout,这样recyclerview就自动拥有了下拉刷新功能了。另外需要注意,由于recyclerview现在变成了swipeRefreshLayout的子控件,因此之前使用app:layout_behavior声明的布局行为现在要移到swipeRefreshLayout中才行。

                  <androidx.swiperefreshlayout.widget.SwipeRefreshLayout
                      android:id="@+id/swipe_refresh"
                      android:layout_width="match_parent"
                      android:layout_height="match_parent"
                      app:layout_behavior="@string/appbar_scrolling_view_behavior">
                  <androidx.recyclerview.widget.RecyclerView
                      android:id="@+id/recycer_view"
                      android:layout_width="match_parent"
                      android:layout_height="match_parent"
                      app:layout_behavior="@string/appbar_scrolling_view_behavior"/>
                  </androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
      
    • 修改mainactivity中的代码:

      • 首先调用SwipeRefreshLayout的setColorSchemeResources()方法来设置下拉刷新进度条的颜色,
      • 然后调用setOnRefreshListener()方法来设置一个下拉刷新的监听器,当用户进行了刷新操作时,就会调用lambda表达式中的逻辑。
      • 然后创建新的线程进行刷新,当刷新结束后,将refreshing设置为false表示刷新结束,隐藏进度条。
              // 关于下拉刷新
              swipeRefresh =(SwipeRefreshLayout) findViewById(R.id.swipe_refresh);
              swipeRefresh.setColorSchemeResources(R.color.design_default_color_on_primary);
              swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                  @Override
                  public void onRefresh() {
                      refreshFruits(adapter);
                  }
              });
          }
      
          private void refreshFruits(FruitAdapter adapter) {
              new Thread(()->{
                  try {
                      Thread.sleep(2000);
                  } catch (InterruptedException e) {
                      e.printStackTrace();
                  }
                  runOnUiThread(()->{
                      initFruits();
                      adapter.notifyDataSetChanged();
                      swipeRefresh.setRefreshing(false);
                  });
              }).start();
          }
      

    可折叠式标题

    实际上,我们可以根据自己的喜好随意制定标题栏的样式。下面市县一个可折叠标题栏的效果。

    CollapsingToolbarLayout

    collapsingToolbarlayout是一个作用与toolbar基础之上的布局,它也是由material库提供的。不过他是不能独立存在的,只能作为appbarlayout的直接子布局来使用。而appbarlayout又必须是coordinatorlayout的子布局。解决:

    首先额外创建一个水果的详细展示,FruitActivity。包括布局和activity。

    <androidx.coordinatorlayout.widget.CoordinatorLayout 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=".FruitActivity">
            <!--    水果标题栏 -->
        <com.google.android.material.appbar.AppBarLayout
            android:id="@+id/app_bar"
            android:layout_width="match_parent"
            android:layout_height="250dp">
            <com.google.android.material.appbar.CollapsingToolbarLayout
                android:id="@+id/collapsing_toolbar"                                                       
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
                app:contentScrim="@color/design_default_color_primary"
                app:layout_scrollFlags="scroll|exitUntilCollapsed">
                <ImageView
                    android:id="@+id/fruit_iamge_view"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:scaleType="centerCrop"
                    app:layout_collapseMode="parallax"/>
    
                <androidx.appcompat.widget.Toolbar
                    android:id="@+id/toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="?attr/actionBarSize"
                    app:layout_collapseMode="pin"/>
            </com.google.android.material.appbar.CollapsingToolbarLayout>
        </com.google.android.material.appbar.AppBarLayout>
    </androidx.coordinatorlayout.widget.CoordinatorLayout>
    

    CollapsingToolbarLayout这个布局:

    • android:theme属性指定了一个主题
    • app:contentScrim属性用于指定CollapsingToolBarLayout在趋于折叠以及折叠之后的背景色。【折叠了就是一个普通的toolbar】
    • app:layouy_scrollFlags属性是指定滚动时候的几种状态:
      • scroll表示当recyclerview向上滚动的时候,toolbar会一起向上滚动,并实现隐藏。
      • exitUntilCollapsed表示当CollapsingToolbarLayout随着棍等完成折叠之后就保留在界面上,不再移除屏幕。
    • 最后再collapingtoolbarlayout中定义了标题栏的具体内容。
      • app:layout_collapseMode用于指定大年控件在collapsingtoolbarlayout折叠过程中的折叠模式,
      • bin模式表示在折叠的过程中,位置始终保持不变
      • parallax模式表示在折叠过程中产生一定的错位偏移。

    在完成了标题栏以后开始写水果内容,这个地方使用MaterialCardView

            <!--    水果标题栏 -->
    		<!-- .... -->
    	<!--    水果内容栏-->
        <androidx.core.widget.NestedScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent">
                <com.google.android.material.card.MaterialCardView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="15dp"
                    android:layout_marginLeft="15dp"
                    android:layout_marginRight="15dp"
                    android:layout_marginTop="35dp"
                    app:cardCornerRadius="4dp">
                    <TextView
                        android:id="@+id/fruit_content_text"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_margin="10dp"/>
                </com.google.android.material.card.MaterialCardView>
    
            </LinearLayout>
        </androidx.core.widget.NestedScrollView>
    

    最后,在activity_fruit添加上一个悬浮按钮:

    	<!--    水果内容栏-->    
    </androidx.core.widget.NestedScrollView>
    
        <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="16dp"
            android:src="@drawable/ic_comment"
            app:layout_anchor="@id/app_bar"
            app:layout_anchorGravity="bottom|end"/>
    </androidx.coordinatorlayout.widget.CoordinatorLayout>
    

    关于activity的代码:

    • 首先,在onCreate()方法中,我们通过Intent获取到传入的水果名和水果图片的资源id。

    • 然后,通过findViewById()方法拿到刚才在布局文件中定义的各个控件的实例。

    • 接着就是使用Toolbar的标准方法,将它作为ActionBar显示,并启用HomeAsUp按钮。

        public static final String FRUIT_NAME = "fruit_name";
        public static final String FRUIT_IMAGE_ID = "fruit_image_id";
        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_fruit);
            Intent intent =getIntent();
            String fruitName = intent.getStringExtra(FRUIT_NAME);
            int fruitImageId = intent.getIntExtra(FRUIT_IMAGE_ID,0);
            Toolbar toolbar =(Toolbar) findViewById(R.id.toolbar); // 注意toolbar有两个!!
            CollapsingToolbarLayout collapsingToolbar =(CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
            ImageView fruitImageView = (ImageView) findViewById(R.id.fruit_image_view);
            TextView fruitContentText =(TextView) findViewById(R.id.fruit_content_text);
            setSupportActionBar(toolbar);
            ActionBar actionBar = getSupportActionBar();
            if(actionBar!=null){
                actionBar.setDisplayHomeAsUpEnabled(true);
            }
            collapsingToolbar.setTitle(fruitName);
            Glide.with(this).load(fruitImageId).into(fruitImageView);
            String fruitContent = generateFruitContent(fruitName);
            fruitContentText.setText(fruitContent);
        }
    
        private String generateFruitContent(String fruitName) {
            StringBuilder sb = new StringBuilder();
            for(int i=0;i<500;i++){
                sb.append(fruitName);
            }
            return sb.toString();
        }
    
        @Override
        public boolean onOptionsItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()){
                case android.R.id.home:
                    finish();
                    return true;
            }
            return super.onOptionsItemSelected(item);
        }
    

    当完成了FruitActivity的相关代码后,需要做的就是当在MainActivity中点击recyclerView的时候,回调这个FruitActivity。这个部分在第三节UI的RecyclerView的点击事件也讲过,其代码实际上是写在FruitAdapter中:

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            if(mcontext == null){
                mcontext = parent.getContext();
            }
            View view = LayoutInflater.from(mcontext).inflate(R.layout.fruits_item,parent,false);
            // 添加部分@!!!
            final ViewHolder holder = new ViewHolder(view);
            holder.cardView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int position = holder.getAdapterPosition();
                    Fruit fruit = mFruitList.get(position);
                    Intent intent= new Intent(mcontext, FruitActivity.class);
                    intent.putExtra(FruitActivity.FRUIT_NAME,fruit.getName());
                    intent.putExtra(FruitActivity.FRUIT_IMAGE_ID,fruit.getImageId());
                    mcontext.startActivity(intent);
                }
            });
    
            return holder;
        }
    

    完成以上内容后,就可以通过intent从MainActivity转到FruitActivity了。

    充分利用系统状态栏空间

    想要让背景图和系统状态栏融合,需要借助android:fitsSystemWindows这个属性来实现。在CoordinatorLayoutAppBarLayoutCollapsingToolbarLayout这种嵌套结构的布局中,将控件android:fitsSystemWindows属性指定为true,就表示该控件会出现在系统状态栏里。

    最后要给ImageView设置这个属性,同时对每个父布局都设置这个属性。

    另外,我们还必须在程序的主题中将状态栏颜色指定成透明色才行,具体在res/values/themes.xml中指定:

    <resources>
    
        <style name="FruitActivityTheme" parent="Theme.MaterialTest">
            <item name="android:statusBarColor">@android:color/transparent</item>
        </style>
    </resources>
    

    同时在manifest中给该活动设置该theme:

            <activity
                android:name=".FruitActivity"
                android:theme="@style/FruitActivityTheme"></activity>
            <activity
    
  • 相关阅读:
    如何查看ubuntu版本
    基于Python与命令行人脸识别项目(系列一)
    问题 B: Curriculum Vitae
    问题 M: 克隆玩具
    1906: 鹊桥相会
    3265: 聪明的矿工
    2363: 完美旗手队列
    2545: 内部收益率
    2544: 台球碰撞
    3272: 公民身份号码
  • 原文地址:https://www.cnblogs.com/SsoZhNO-1/p/14184106.html
Copyright © 2020-2023  润新知