Android第一行代码——第13章Material Design实战

什么是Material Design

Material Design 是谷歌的一套全新的界面设计语言,包含了视觉,运动,互动效果等特性。
Design Support库,将Material Design中最具代表性的一些控件和效果进行了封装。

Toolbar

Toolabr继承了ActionBar的所有功能,,灵活性很高,而且可配合其他控件来完成一些Material Design效果。

创建的基本步骤:
1.更改程序的ActionBar主题
2.在布局中添加Toolbar控件
3.活动中设置支持动作栏
示例:
1.
把之前默认的深色主题改为不带ActionBar的主题

<resources>
    <!-- Base application theme. -->
    <!-- Theme.AppCompat.Light.NoActionBar不带标题栏淡色主题 -->
    <!-- Theme.AppCompat.Light.NoActionBar不带标题栏的深色主题 -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

</resources>

在这里插入图片描述
2.

<androidx.appcompat.widget.Toolbar
	  android:layout_width="match_parent"
	  android:layout_height="?attr/actionBarSize"
	  android:id="@+id/toolbar"
	  android:background="?attr/colorPrimary"
	  android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
	  app:popupTheme="@style/ThemeOverlay.AppCompat.Light"         
                />
     <!-- android:theme 设置Toolbar的主题风格-->
     <!-- app:popupTheme 单独指定弹出的菜单项的主题-->           
 Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
 setSupportActionBar(toolbar);


修改标题栏上显示的文字内容

 <activity
       android:name=".MainActivity"
       android:label="在这修改">    
</activity>

  在activity标签中修改,如果没有指定,默认用application中指定的label内容。

添加action按钮
 和添加普通菜单流程基本一样。
1.创建菜单项的xml文件
注:
  app:showAsAction 指示按钮的显示位值,always:永远显示在Toolbar中,ifRoom:屏幕空间足够的情况下显示在Toolbar中,never:永远显示在菜单中
 如果菜单项指定图标,Toolbar的action按钮只显示图标,菜单中的action只显示文字

<?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/item1"
        android:title="Backup"
        android:icon="@mipmap/ic_launcher"
        app:showAsAction="always"/>
    <item
        android:id="@+id/item2"
        android:title="Delete"
        app:showAsAction="ifRoom"/>
    <item
        android:id="@+id/item3"
        android:title="Setting"
        app:showAsAction="never"/>

</menu>

2.加载菜单文件

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
    
    
        getMenuInflater().inflate(R.menu.toolbarmenu,menu);
        return true;
    }

3.设置点击事件

 @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
    
    
        switch (item.getItemId()){
    
    
            case R.id.backup:
                Toast.makeText(this,"you clicked Backup",Toast.LENGTH_SHORT).show();
                break;
            case R.id.delete:
                Toast.makeText(this,"you clicked delete",Toast.LENGTH_SHORT).show();
                break;
            case R.id.settings:
                Toast.makeText(this,"you clicked settings",Toast.LENGTH_SHORT).show();
                break;
           
        }
        return true;
    }

滑动菜单

示例:
在这里插入图片描述

DrawerLayout

DrawerLayout控件可用来实现滑动菜单的效果。首先它是一个布局,在布局中允许放入两个直接子控件,第一个子控件用于显示主屏幕中的内容,第二个子控件用于显示滑动菜单中的内容
示例:

<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <FrameLayout
        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/colorPrimary"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />


    </FrameLayout>

    <TextView
        android:id="@+id/text_view"
        android:text="This is menu"
        android:background="#fff"
        android:textSize="30sp"
        android:layout_gravity="start"//侧拉栏的布局必须声明这一属性,left表示侧拉栏在左,right表示侧拉栏在右,start则会根据系统语言来自动选择
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</androidx.drawerlayout.widget.DrawerLayout>

设置友好提示
 滑动菜单只有在屏幕的边缘进行拖动时才将菜单拖出来,有些用户可能不知道这个功能,Material Design建议的做法是在Toolbar左边加一个导航按钮。
代码实现:

 	private DrawerLayout drawerLayout;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
      
        Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        
        drawerLayout = (DrawerLayout)findViewById(R.id.drawerLayout);
        
        ActionBar actionBar = getSupportActionBar();
        if(actionBar != null){
    
    
            actionBar.setDisplayHomeAsUpEnabled(true);      //让导航按钮显示出来
            actionBar.setHomeAsUpIndicator(R.mipmap.ic_launcher);   //设置导航按钮图标,默认是返回的图标
        }
    }
      @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
    
    
        switch (item.getItemId()){
    
    
          ...
            case android.R.id.home:
                drawerLayout.openDrawer(GravityCompat.START);
                //将滑动菜单展示出来
        }
        return true;
    }

NavigationView

NavigationView是Design Support库中的一个控件,借助它,可让滑动菜单页面的实现变得简单。

  1. 添加依赖
implementation 'com.android.support:design:28.0.0'
implementation 'de.hdodenhof:circleimageview:3.1.0'

第二个是开源项目CircleimageView的依赖,GitHub地址,借助它可轻松实现图片圆形化的功能。

  1. 准备menu

在menu下新建xml文件

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <group
        android:checkableBehavior="single">
        <!-- group表示一个组,android:checkableBehavior="single"表示组中的所有菜单项只能单选 -->
        <item
            android:id="@+id/item_cgl1"
            android:title="grape"
            android:icon="@drawable/grape"/>
        <item
            android:id="@+id/item_cgl2"
            android:title="orange"
            android:icon="@drawable/orange"/>
        <item
            android:id="@+id/item_cgl3"
            android:title="pear"
            android:icon="@drawable/pear"/>
        <item
            android:id="@+id/item_cgl4"
            android:title="watemelon"
            android:icon="@drawable/watemelon"/>
    </group>


</menu>
  1. 写headLayout
<?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">          <!-- 180dp是NavigationView比较合适的高度 -->
    <de.hdodenhof.circleimageview.CircleImageView
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:id="@+id/header_image"
        android:src="@drawable/pear"
        android:layout_centerInParent="true"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/header_textView1"
        android:text="[email protected]"
        android:textSize="14sp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:textColor="#191515"
        />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/header_textView2"
        android:text="GOON TST"
        android:textSize="14sp"
        android:layout_above="@id/header_textView1"
        android:textColor="#150A0A"
        />


</RelativeLayout>
  1. 使用NavigationView
<androidx.drawerlayout.widget.DrawerLayout 
	.......
    <com.google.android.material.navigation.NavigationView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/nav_view"
        android:layout_gravity="start"
        app:menu="@menu/circleimagemenu"
        app:headerLayout="@layout/headerlayout"/>
        <!-- app:menu 显示具体菜单项 -->
       	<!-- app:headerLayout 显示头部布局 -->
</androidx.drawerlayout.widget.DrawerLayout>

5.处理菜单项的点击事件

 navigationView.setCheckedItem(R.id.item_cgl1);      //设置菜单项的默认选中
        //对菜单项设置监听
        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
    
    
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
    
    
                drawerLayout.closeDrawers();        //将滑动菜单关闭
                return true;
            }
        });

悬浮按钮和可交互提示

悬浮按钮

悬浮按钮就是我们常见的桌面悬浮球
用法示例:

  1. 在布局中添加
<com.google.android.material.floatingactionbutton.FloatingActionButton
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:id="@+id/fab"
     android:src="@drawable/pear"
     android:layout_gravity="bottom|right"
     android:layout_margin="16dp"
     app:elevation="8dp"
 />
 <!-- elevation给FloatingActionButton指定一个高度值,高度值越大,
 	   投影范围越大,投影效果越淡 -->
  1. 点击事件
 //FloatingActionButton点击事件
		FloatingActionButton floatingActionButton = (FloatingActionButton)findViewById(R.id.fab);
        floatingActionButton.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View v) {
    
                 
            	Toast.makeText(MainActivity.this,"click",Toast.LENGTH_SHORT).show();
            }
        });

Snackbar

Snackbar是Design Support库提供的更加先进的提示工具,允许在提示中加入一个可交互按钮,让用户点击按钮时可以执行一些额外的逻辑操作。
用法:
和Toast类似,改写刚才的点击事件

//FloatingActionButton点击事件
        FloatingActionButton floatingActionButton = (FloatingActionButton)findViewById(R.id.fab);
        floatingActionButton.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View v) {
    
    
                Snackbar.make(v,"Data delete",Snackbar.LENGTH_SHORT)
                //添加按钮
                        .setAction("Undo", new View.OnClickListener() {
    
    
                            @Override
                            public void onClick(View v) {
    
    
                                Toast.makeText(MainActivity.this,"click",Toast.LENGTH_SHORT).show();
                            }
                        })
                        .show();

            }
        });

CoordinatorLayout

CoordinatorLayout是一个加强版的FrameLayout,可以监听所有子控件的各种事件,自动帮我们做出最为合理的响应
在刚才的Snackbar弹出后会遮挡FloatingActionButton,如果我们使用CoordinatorLayout布局,他可以监听到Snackbar的弹出事件,它会自动将内部的FloatingActionButton向上偏移。
用法示例:
直接把刚才的FrameLayout替换成CoordinatorLayout

<androidx.coordinatorlayout.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <com.google.android.material.appbar.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
           ......
    </androidx.coordinatorlayout.widget.CoordinatorLayout>

卡片式布局

CardView

卡片式布局可以让页面中的元素看起开就像在卡片中一样,并且有圆角和投影。它是由appcompat-v7库提供。接下来用Recyclerview进行展示

注:Glide库,GitHub地址,是一个超级强大的图片加载库,不仅可以用来加载本地图片,还可以加载网络图片,GIF图片,甚至是本地视频

  1. 布局文件
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout 
    <androidx.coordinatorlayout.widget.CoordinatorLayout
        ...
            <androidx.recyclerview.widget.RecyclerView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:id="@+id/recyclerview"
                />
	</androidx.coordinatorlayout.widget.CoordinatorLayout>
</androidx.drawerlayout.widget.DrawerLayout>
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_margin="5dp"
    app:cardCornerRadius="4dp"
    >
    <!--  app:cardCornerRadius 设置卡片圆角的弧度-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <ImageView
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:id="@+id/item_image"
            android:scaleType="centerCrop"/>      <!-- 指定图片的缩放模式,他可以让图片保持原有比例填充ImageView,并裁掉超出部分 -->
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/item_textview"
            android:layout_gravity="center_horizontal"
            android:layout_margin="5dp"
            android:textSize="16sp"/>
    </LinearLayout>


</androidx.cardview.widget.CardView>
  1. 代码部分
    Fruit.class
package com.example.revise_12_1;

public class Fruit {
    
    
    private String Name;
    private int imageId;

    public Fruit(String name, int imageId) {
    
    
        Name = name;
        this.imageId = imageId;
    }

    public String getName() {
    
    
        return Name;
    }

    public int getImageId() {
    
    
        return imageId;
    }
}

Myadapt.class

public class Mydapt extends RecyclerView.Adapter<Mydapt.ViewHolder> {
    
    
    private List<Fruit> list;
    private Context mcontext;
    public Mydapt(List<Fruit> list) {
    
    
        this.list = list;
    }

    class ViewHolder extends RecyclerView.ViewHolder{
    
    
        CardView cardView;
        ImageView imageView;
        TextView textView;

        public ViewHolder(@NonNull View itemView) {
    
    
            super(itemView);
            cardView = (CardView) itemView;
            imageView = itemView.findViewById(R.id.item_image);
            textView = itemView.findViewById(R.id.item_textview);
        }
    }
    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    
    
        if(mcontext==null){
    
    
            mcontext = parent.getContext();
        }
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item,parent,false);
        ViewHolder viewHolder = new ViewHolder(view);

        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
    
    
        Fruit fruit = list.get(position);
        holder.textView.setText(fruit.getName());
        Glide.with(mcontext).load(fruit.getImageId()).into(holder.imageView);       //用Glide加载图片

    }

    @Override
    public int getItemCount() {
    
    
        return list.size();
    }


}

MainActivity

	private Mydapt adapt;
    private List<Fruit> list = new ArrayList<>();

	
		addlist();
        RecyclerView recyclerView = (RecyclerView)findViewById(R.id.recyclerview);
        GridLayoutManager manager = new GridLayoutManager(MainActivity.this,2);
        adapt = new Mydapt(list);
        recyclerView.setLayoutManager(manager);
        recyclerView.setAdapter(adapt);


	private void addlist() {
    
    
        list.clear();
        Fruit[] fruits = {
    
    new Fruit("grape",R.drawable.grape),new Fruit("orange",R.drawable.orange),
                new Fruit("pear",R.drawable.pear),new Fruit("watemelon",R.drawable.watemelon)};
        for(int i  =0; i < 50 ;i++){
    
    
            Random random = new Random();
            int index = random.nextInt(fruits.length);
            list.add(fruits[index]);
        }
    }

AppBarLayout

 刚才在运行程序后会出现RecyclerView遮挡Toolbar的情况,是由于CoordinatorLayout布局是一个加强版的FrameLayout,所有控件在不进行明确定位的情况下会默认摆放在布局左上角。
 我们可用AppBarLayout来解决,它实际上是一个垂直方向的LinearLayout,他的内部做了很多滚动事件的封装
 注:
AppBarLayout 只有作为 CoordinatorLayout 的直接子 View 时才能正常工作,为了让 AppBarLayout 能够知道何时滚动其子 View,
我们还应该在 CoordinatorLayout 布局中提供一个可滚动 View,我们称之为 Scrolling View。
Scrolling View 和 AppBarLayout 之间的关联,通过将 Scrolling View 的 Behavior 设为 AppBarLayout.ScrollingViewBehavior 来建立。

用法示例:
1.将AppBarLayout镶嵌到Toolbar中
2.指定Recyclerview的布局行为

<androidx.coordinatorlayout.widget.CoordinatorLayout
       ......
        <com.google.android.material.appbar.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <androidx.appcompat.widget.Toolbar
                ......
                app:layout_scrollFlags="scroll|enterAlways|snap"
                />
  <!-- layout_scrollFlags :
  		scroll表示向上滚动时Toolbar滚动并实现隐藏,
  		enenterAlways表示向下滚动时Toolabr向下滚动并重现
        snap表示当Toolbar还没有完全隐藏或显示时,根据当前滚动的距离,
        选择隐藏还是显示 
 -->

        </com.google.android.material.appbar.AppBarLayout>
         <androidx.recyclerview.widget.RecyclerView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:id="@+id/recyclerview"
                app:layout_behavior="@string/appbar_scrolling_view_behavior"
           />
    </androidx.coordinatorlayout.widget.CoordinatorLayout>

&emsp

下拉刷新

SwipeRefreshLayout类是实现下拉刷新功能的核心类。
用法示例:
给Recyclerview添加下拉刷新功能

  1. 在布局中添加SwipeRefreshLayout
 <androidx.swiperefreshlayout.widget.SwipeRefreshLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/srf"
            app:layout_behavior="@string/appbar_scrolling_view_behavior">

            <androidx.recyclerview.widget.RecyclerView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:id="@+id/recyclerview"
                />

        </androidx.swiperefreshlayout.widget.SwipeRefreshLayout>

由于是给RecyclerView添加下拉刷新,直接在RecyclerView的外层嵌套

2.刷新逻辑:

private SwipeRefreshLayout swipeRefreshLayout;
protected void onCreate(Bundle savedInstanceState) {
    
    
       ......
        //下拉刷新:
        swipeRefreshLayout = (SwipeRefreshLayout)findViewById(R.id.srf);
        swipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary);       
        //设置颜色
        //下拉刷新的监听器
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
    
    
            @Override
            public void onRefresh() {
    
    
                refreshFruits();
            }
        });

    }
     private void refreshFruits() {
    
    
        new Thread(new Runnable() {
    
    
            @Override
            public void run() {
    
    
                try {
    
    
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
    
    
                    e.printStackTrace();
                }
                runOnUiThread(new Runnable() {
    
    
                    @Override
                    public void run() {
    
    
                        addlist();
                        adapt.notifyDataSetChanged();
                        swipeRefreshLayout.setRefreshing(false);        
                        //刷新事件结束,并隐藏刷新进度条
                    }
                });
            }
        }).start();
    }

可折叠式标题栏

CollapsingToolbarLayout

CollapsingToolbarLayout是一个作用于Toolbar基础之上的布局,可以让Toolbar的效果更华丽,只能作为AppBarLayout的直接子类布局使用。
用法示例:
新建一个活动,修改布局文件如下:

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="250dp"
        android:id="@+id/appbar">
        <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/colorPrimary"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">
    <!--exitUntilCollapsed随着滚动完成折叠之后就保留在界面上,不在移出屏幕 -->
            <ImageView
                android:id="@+id/image2"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:scaleType="centerCrop"
                app:layout_collapseMode="parallax"/>
            <androidx.appcompat.widget.Toolbar
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:id="@+id/toolbar2"
                app:layout_collapseMode="pin"/>
    <!--app:layout_collapseMode指定折叠模式
		parallax  在折叠过程中出现一定的错位
		pin 在折叠过程中位置始终保持不变
    -->            
        </com.google.android.material.appbar.CollapsingToolbarLayout>
    </com.google.android.material.appbar.AppBarLayout>



    <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="wrap_content"
            android:orientation="vertical">
            <androidx.cardview.widget.CardView
                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/textview2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_margin="10dp"
                    />

            </androidx.cardview.widget.CardView>
        </LinearLayout>
    </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/pear"
        app:layout_anchor="@id/toolbar2"
        app:layout_anchorGravity="bottom|end"/>
    <!--layout_anchor设置瞄点 -->



</androidx.coordinatorlayout.widget.CoordinatorLayout>

NestedScrollView布局用于显示水果详情,增强版的ScrollView,不仅允许使用滚动的方式来查看屏幕以外的数据,而且还增加了响应滚动事件的功能。
注:它的内部只允许出现一个直接子布局
活动逻辑代码:

public class FruitActivity extends AppCompatActivity {
    
    
    public static final String FRUIT_NAME = "fruit_name";
    public static final String FRUIT_IMAGE_ID = "fruit_image_id";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fruit);
        Intent intent = getIntent();
        String fruitName = intent.getStringExtra(FRUIT_NAME);
        int imageId = intent.getIntExtra(FRUIT_IMAGE_ID,0);
		
        Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
        CollapsingToolbarLayout collapsingToolbarLayout = (CollapsingToolbarLayout)findViewById(R.id.collapsing_toolbar);
        ImageView imageView = (ImageView)findViewById(R.id.fruit_image_view);
        TextView textView = (TextView)findViewById(R.id.fruit_content_text);
        
        setSupportActionBar(toolbar);	//设置支持标题栏
        //设置返回键
        ActionBar actionBar = getSupportActionBar();
        if(actionBar != null){
    
    
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
        
        collapsingToolbarLayout.setTitle(fruitName);
        Glide.with(this).load(imageId).into(imageView);
        String fruitContent = geterateFruitContent(fruitName);
        textView.setText(fruitContent);
    }

    private String geterateFruitContent(String fruitName) {
    
    
        StringBuilder fruitContent = new StringBuilder();
        for(int i = 0;  i < 500; i++){
    
    
            fruitContent.append(fruitName);
        }
        fruitContent.reverse();
        return fruitContent.toString();
    }
	//返回键执行的逻辑
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
    
    
        switch (item.getItemId()){
    
    
       
            case android.R.id.home:
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

主活动调用代码;
设置RecyclerView的点击事件

public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    
    
        if(mContext==null)
            mContext = parent.getContext();
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item,parent,false);
        final ViewHolder viewHolder = new ViewHolder(view);
        viewHolder.cardView.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View v) {
    
    
                int position = viewHolder.getAdapterPosition();
                Fruit fruit = list.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 viewHolder;
    }

效果展示:
在这里插入图片描述

完整代码

GitHub地址

猜你喜欢

转载自blog.csdn.net/haazzz/article/details/108807247