Material Design(2)
1.卡片式布局
1.CardView
CardView也是一个FrameLayout,只是额外增加了圆角和阴影等效果,看上去会有立体的效果。
接下来我们将结合RecyclerView来实现一个高配版的水果列表效果(其实只需要在RecyclerView的子布局中使用CardView)
1.添加依赖
implementation ‘com.android.support:recyclerview-v7:24.2.1’
implementation ‘com.android.support:cardview-v7:24.2.1’
implementation 'com.github.bumptech.glide:glide:3.7.0’
第三个是一个Glide库的依赖,Glide是一个强大的图片加载器,而且Glide用法简单。
2.布局文件
<?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:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/drawer_layout">
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.appcompat.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:id="@+id/toolbar2"
android:background="?attr/colorPrimary" android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" app:popupTheme="@style/ThemeOverlay.AppCompat.Light" app:layout_scrollFlags="scroll|enterAlways|snap">
</androidx.appcompat.widget.Toolbar>
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/recycler_view"/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
<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/nav_menu"
app:headerLayout="@layout/nav_header"/>
</androidx.drawerlayout.widget.DrawerLayout>
在CoordinatorLayout中添加一个RecyclerView
3.定义Fruit类
public class Fruit {
private String name;
private int imageId;
public Fruit(String name, int imageId) {
this.name = name;
this.imageId = imageId;
}
public String getName() {
return name;
}
public int getImageId() {
return imageId;
}
}
4.定义RecyclerView的子布局
<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">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:layout_width="match_parent"
android:layout_height="100dp"
android:id="@+id/fruit_image"
android:scaleType="centerCrop"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/fruit_name"
android:layout_gravity="center_horizontal"
android:layout_margin="5dp"
android:textSize="16sp"/>
</LinearLayout>
</androidx.cardview.widget.CardView>
使用CardView来作为子项的最外层布局,从而使得RecyclerView中的每个元素都是在卡片当中的。CardView是一个FrameLayout,因此它没有什么方便的定位方式,所以我们在CardView里面再嵌套一个LinearLayout,然后在LinearLayout中放置具体的内容。
5.适配器
public class FruitAdapter extends RecyclerView.Adapter<FruitAdapter.ViewHolder>{
private Context context;
private List<Fruit> fruitList;
static class ViewHolder extends RecyclerView.ViewHolder{
CardView cardView;
ImageView fruitImage;
TextView fruitName;
public ViewHolder(View view){
super(view);
cardView = (CardView)view;
fruitImage = view.findViewById(R.id.fruit_image);
fruitName = view.findViewById(R.id.fruit_name);
}
}
public FruitAdapter(List<Fruit> fruitList) {
this.fruitList = fruitList;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
if (context==null){
context=parent.getContext();
}
View view = LayoutInflater.from(context).inflate(R.layout.fruit_item,parent,false);
final ViewHolder holder = new ViewHolder(view);
holder.cardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int position = holder.getAdapterPosition();
Fruit fruit = fruitList.get(position);
Intent intent = new Intent(context,FruitActivity.class);
intent.putExtra(FruitActivity.FRUIT_NAME,fruit.getName());
intent.putExtra(FruitActivity.FRUIT_IMAGE_ID,fruit.getImageId());
context.startActivity(intent);
}
});
return holder;
}
@Override
public void onBindViewHolder(@NonNull final ViewHolder holder, int position) {
Fruit fruit = fruitList.get(position);
holder.fruitName.setText(fruit.getName());
Glide.with(context).load(fruit.getImageId()).into(holder.fruitImage);
}
@Override
public int getItemCount() {
return fruitList.size();
}
}
这个和之前RecyclerView中的没有什么差别,唯一不同的是在onBindViewHolder()方法中我们使用了Glide加载图片。
首先调用Glide.with()方法传入一个Context,Activity或Fragment参数,然后调用load()方法去加载图片,可以是一个url地址,也可以是一个本地路径,或者是一个资源id,最后调用into()方法将图片设置到某一个ImageView中就行了。
6.最终
public class Second extends AppCompatActivity implements View.OnClickListener{
private DrawerLayout drawerLayout;
private Fruit[] fruits = {new Fruit("apple",R.mipmap.szb),new Fruit("banana",R.mipmap.szb),new Fruit("orange",R.mipmap.szb),new Fruit("watermelon",R.mipmap.szb)
,new Fruit("pear",R.mipmap.szb),new Fruit("grape",R.mipmap.szb),new Fruit("pineapple",R.mipmap.szb)
,new Fruit("strawberry",R.mipmap.szb),new Fruit("cherry",R.mipmap.szb),new Fruit("mango",R.mipmap.szb)};
private List<Fruit> list = new ArrayList<>();
private FruitAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
drawerLayout = findViewById(R.id.drawer_layout);
Toolbar toolbar = findViewById(R.id.toolbar2);
setSupportActionBar(toolbar);
NavigationView navigationView = findViewById(R.id.nav_view);
ActionBar actionBar = getSupportActionBar();
if(actionBar!=null){
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(R.mipmap.menu);
}
navigationView.setCheckedItem(R.id.nav_friends);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
drawerLayout.closeDrawers();
return true;
}
});
initFruits();
RecyclerView recyclerView = findViewById(R.id.recycler_view);
GridLayoutManager layoutManager = new GridLayoutManager(this,2);
recyclerView.setLayoutManager(layoutManager);
adapter = new FruitAdapter(list);
recyclerView.setAdapter(adapter);
}
private void initFruits(){
list.clear();
for(int i = 0;i<50;i++){
Random random = new Random();
int index = random.nextInt(fruits.length);
list.add(fruits[index]);
}
}
public void onClick(View v){
Snackbar.make(v,"Data deleted",Snackbar.LENGTH_SHORT)
.setAction("Undo", new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(Second.this, "Data restored", Toast.LENGTH_SHORT).show();
}
}).show();
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch(item.getItemId()){
case android.R.id.home:
drawerLayout.openDrawer(GravityCompat.START);
break;
}
return true;
}
}
7.效果
我们会发现一个问题,ToolBar被RecyclerView遮挡住了,要解决这个问题,就得用到下面的工具了
2.AppBarLayout
AppBarLayout实际上是一个垂直方向上的LinearLayout,他在内部做了很多滚动事件的封装,并应用了MaterialDesign的设计理念
第一步,将ToolBar嵌套在AppBarLayout中,第二步给RecyclerView指定一个布局行为。
<androidx.drawerlayout.widget.DrawerLayout 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"
android:id="@+id/drawer_layout">
<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.appcompat.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:id="@+id/toolbar2"
android:background="?attr/colorPrimary"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
app:layout_scrollFlags="scroll|enterAlways|snap">
</androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.AppBarLayout>
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/recycler_view" app:layout_behavior="@string/appbar_scrolling_view_behavior"/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
<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/nav_menu"
app:headerLayout="@layout/nav_header"/>
</androidx.drawerlayout.widget.DrawerLayout>
Toolbar中的app:layout_scrollFlags属性,scroll表示当RecyclerView向上滚动的时候,Toolbar会跟着向上移动并实现隐藏,enterAlways表示当recyclerview向下滚动时,Toolbar会跟着一起向下滚动并重新显示,snap表示当Toolbar还没有完全隐藏或显示的时候,会根据当前滚动的距离,自动选择隐藏还是显示。
2.下拉刷新SwipeRefreshLayout
使用下拉刷新,只需要把想要实现下拉刷新的控件放在SwipRefreshLayout中就可以了。
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
android:id="@+id/swip_refresh"
android:layout_width="match_parent"
android:layout_height="match_parent"
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/recycler_view"
app:layout_behavior="@string/appbar_scrolling_view_behavior"/>
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
因为RecyclerView现在变成了SwipeRefreshLayout的子控件,所以之前使用的app:layout_behavior声明的布局行为现在得放在SwipeRefreshLayout中。
然后在Activity中添加处理逻辑。
private SwipeRefreshLayout swipeRefreshLayout;
swipeRefreshLayout = findViewById(R.id.swip_refresh);
swipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
resreshFruits();
}
});
private void resreshFruits(){
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
@Override
public void run() {
initFruits();
adapter.notifyDataSetChanged();
swipeRefreshLayout.setRefreshing(false);
}
});
}
}).start();
}
通常情况下onRefresh()方法中应该是去网络上请求最新的数据,然后再将这些数据展示出来。
3.可折叠式标题栏
CollapsingToolbarLayout
CollapsingToolbarLayout是一个作用于Toolbar基础之上的布局,它是不能独立存在的,它在设计的时候就被限定只能作为AppBarLayout的直接子布局来使用,而AppBarLayout又必须是CoordinayorLayout的子布局。
1.创建一个FruitActivity活动
xml
<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:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/collapsing_toolbar"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:contentScrim="?attr/colorPrimary"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
>
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/fruit_image_view"
android:scaleType="centerCrop"
app:layout_collapseMode="parallax"/>
<androidx.appcompat.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:id="@+id/toolbar"
app:layout_collapseMode="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_marginRight="15dp"
android:layout_marginTop="35dp"
app:cardCornerRadius="4dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/fruit_content_text"
android:layout_margin="10dp"/>
</androidx.cardview.widget.CardView>
</LinearLayout>
</androidx.core.widget.NestedScrollView>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
首先用CoordinatorLayout作为最外层的布局,接着在CoordinatorLayout嵌套一个AppBarLayout,然后再在AppBarLayout里嵌套一个CollapsingToolbarLayout。app:contentScrim用于指定CollapsingToolbarLayout在趋于折叠状态以及折叠之后的背景色,app:layout_scrollFlags之前也是用过的,scroll表示CollapsingToolbarLayout会随着水果内容详情的滚动一起滚动,exitUntilCollapsed表示当CollapsingToolbarLayout随着滚动完成之后就保留在界面上,不再移出屏幕。
然后我们在CollapsingToolbarLayout中定义标题栏的内容,定义了一个ImageView和Toolbar,也就意味着,这个高级版的标题栏是由普通的标题栏加上图片组成的。app:layout_collapseMode用于指定当前控件在CollaspingToolbarLayout折叠过程中的折叠模式,pin表示在折叠过程中位置保持不变,parallax表示会在折叠过程中产生一定的错位偏移。
标题栏就定义好了,然后是内容部分,水果内容的最外层布局试用了NestedScrollView,它和AppBarLayout是平级的。NestedScrollView在ScrollView的基础上还增加了嵌套响应滚动事件的功能。不管是ScrollView还是NestedScrollView它们的内部只允许存在一个直接子布局,所以通常都会嵌套一个LinearLayout。
然后编写Activity
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 fruitImageId = intent.getIntExtra(FRUIT_IMAGE_ID,0);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
CollapsingToolbarLayout collapsingToolbarLayout = (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);
}
collapsingToolbarLayout.setTitle(fruitName);
Glide.with(this).load(fruitImageId).into(fruitImageView);
String fruitContent = generateFruitContent(fruitName);
fruitContentText.setText(fruitContent);
}
private String generateFruitContent(String fruitName){
StringBuilder fruitContent = new StringBuilder();
for(int i = 0;i<500;i++){
fruitContent.append(fruitName);
}
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 (context==null){
context=parent.getContext();
}
View view = LayoutInflater.from(context).inflate(R.layout.fruit_item,parent,false);
final ViewHolder holder = new ViewHolder(view);
holder.cardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int position = holder.getAdapterPosition();
Fruit fruit = fruitList.get(position);
Intent intent = new Intent(context,FruitActivity.class);
intent.putExtra(FruitActivity.FRUIT_NAME,fruit.getName());
intent.putExtra(FruitActivity.FRUIT_IMAGE_ID,fruit.getImageId());
context.startActivity(intent);
}
});
return holder;
}
在FruitAdapter中设置了点击事件。