主頁 > 前端設計 > Android基礎知識——Material Design實戰

Android基礎知識——Material Design實戰

2020-09-15 03:50:44 前端設計

文章目錄

  • 1.什么是Material Design
  • 2.Toolbar
  • 3.滑動選單
    • 3.1DrawerLayout
    • 3.2NavigationView
  • 4.懸浮按鈕和可互動提示
    • 4.1FloatingActionButton
    • 4.2Snackbar
    • 4.3CoordinatorLayout
  • 5.卡片式布局
    • 5.1CardView
    • 5.2AppBarLayout
  • 6.下拉重繪
  • 7.可折疊式標題欄
    • 7.1CollapsingToolbarLayout
    • 7.2充分利用系統狀態欄空間

1.什么是Material Design

Material Design是由谷歌的設計工程師們基于傳統的優秀設計原則,結合豐富的創意和科學技術所發明的一套全新的界面設計語言,包含了視覺,運動,互動效果等特性,而事實上,Material Design更像是一種設計思想和理念,而本節我們并不是要以設計師的角度去學習Material Design,而是以一個開發者的角度去學習使用一些符合Material Design理念的一些控制元件,

2.Toolbar

Toolbar繼承了ActionBar的所有功能,而且靈活性很高,可以配合其他控制元件來完成一些Material Design的效果,

基本使用步驟:
1.更改程式的標題欄主題,
2.在布局中加入Toolbar,
3.在活動中替換標題欄,

示例:

//步驟一,values下的styles檔案
<resources>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">//因為我們要引入toolbar,所以這里選擇無標題欄主題
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>
</resources>
//步驟二
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    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/colorPrimary"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"//單獨令標題欄為深色主題
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />//令標題欄中的選單項為淺色主題

</LinearLayout>
//步驟三
public class MainActivity extends AppCompatActivity {

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar=(Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);//將標題欄替換為toolbar
    }
}

更改toolbar上顯示的文字:

我們可以在活動中加入android:label屬性來指定toolbar上顯示的文字,

給toolbar添加選單項:

使用步驟與給普通的actionbar添加選單項類似,

示例:

//選單布局
<?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/back"
        android:icon="@drawable/back"
        android:title="Back"
        app:showAsAction="always" />//始終以圖片的形式存在于標題欄

    <item
        android:id="@+id/setting"
        android:icon="@drawable/setting"
        android:title="Setting"
        app:showAsAction="ifRoom" />//如果空間允許則以圖片的形式存在于標題欄,否則以文字的形式

    <item
        android:id="@+id/delete"
        android:icon="@drawable/delete"
        android:title="Delete"
        app:showAsAction="never" />//始終以文字的形式存在于標題欄
</menu>
//活動
public class MainActivity extends AppCompatActivity {

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar=(Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {//引入選單布局
        getMenuInflater().inflate(R.menu.toolbra,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {//給選單中的各個選單項設定點擊事件
        switch (item.getItemId()){
            case R.id.back:
                finish();
                break;
            case R.id.setting:
                Toast.makeText(MainActivity.this,"setting",Toast.LENGTH_SHORT).show();
                break;
            case R.id.delete:
                Toast.makeText(MainActivity.this,"delete",Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
        }
        return true;
    }
}

3.滑動選單

就是我們手機上常見的側拉欄,

3.1DrawerLayout

使用方法:

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>

一個小問題:

這里可能存在一個問題,用戶可能并不知道你的程式會有側拉欄的功能,所以這里谷歌建議我們在標題欄中添加一個側拉欄對應的按鈕,用于打開側拉欄,

示例:

public class MainActivity extends AppCompatActivity {

    private DrawerLayout drawerLayout;

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar=(Toolbar) findViewById(R.id.toolbar);
        drawerLayout=(DrawerLayout) findViewById(R.id.drawer_layout);
        setSupportActionBar(toolbar);
        ActionBar actionBar=getSupportActionBar();
        if(actionBar!=null){
            actionBar.setDisplayHomeAsUpEnabled(true);//toolbar的最左側有一個系統默認存在的按鈕,而該方法能讓該按鈕顯示出來
            actionBar.setHomeAsUpIndicator(R.drawable.ic_menu);//這個按鈕本身的圖案是一個回傳的箭頭,而這里我們可以更改它的圖案
        }
    }

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

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            case android.R.id.home://給這個系統默認存在的按鈕添加點擊事件
                drawerLayout.openDrawer(GravityCompat.START);
                break;
            case R.id.back:
                finish();
                break;
            case R.id.setting:
                Toast.makeText(MainActivity.this,"setting",Toast.LENGTH_SHORT).show();
                break;
            case R.id.delete:
                Toast.makeText(MainActivity.this,"delete",Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
        }
        return true;
    }
}

3.2NavigationView

在上節中我們側拉欄中的內容有些單薄,而NavigationView可以幫助我們很輕松的豐富側拉欄中的內容,

使用步驟:

1.聲名依賴,
2.準備好NavigationView的menu項,
3.準備好NavigationView的headerLayout
4.在布局中加入NavigationView,
5.可以在活動中給NavigationView的各個選單項設定點擊事件,

示例:

//步驟一
dependencies {
    implementation 'com.google.android.material:material:1.2.1'//material design的相關庫
    implementation 'de.hdodenhof:circleimageview:3.1.0'//這是一個開源專案,可以幫助我們很輕松的實作圖片圓形化的功能,
}
//步驟二
<?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/call"
            android:title="Call"
            android:icon="@drawable/nav_call" />

        <item
            android:id="@+id/friends"
            android:title="Friends"
            android:icon="@drawable/nav_friends" />

        <item
            android:id="@+id/location"
            android:title="Location"
            android:icon="@drawable/nav_location" />

        <item
            android:id="@+id/mail"
            android:title="Mail"
            android:icon="@drawable/nav_mail" />

        <item
            android:id="@+id/task"
            android:title="Task"
            android:icon="@drawable/nav_task" />
    </group>
</menu>
//步驟三
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:padding="10dp"
    android:background="@color/colorPrimary"
    android:layout_width="match_parent"
    android:layout_height="180dp">

    <de.hdodenhof.circleimageview.CircleImageView
        android:id="@+id/image_view"
        android:src="@drawable/nav_icon"
        android:layout_centerInParent="true"
        android:layout_width="70dp"
        android:layout_height="70dp" />

    <TextView
        android:id="@+id/mail"
        android:textColor="#fff"
        android:text="mail: 1938796569@qq.com"
        android:layout_alignParentBottom="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/username"
        android:textColor="#fff"
        android:text="username: yangxu"
        android:layout_above="@+id/mail"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</RelativeLayout>
//步驟四
<?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:id="@+id/drawer_layout"
    android:orientation="vertical"
    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>

    <com.google.android.material.navigation.NavigationView
        android:id="@+id/nav_view"
        android:layout_gravity="start"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:menu="@menu/nav_menu"
        app:headerLayout="@layout/header_layout"/>

</androidx.drawerlayout.widget.DrawerLayout>
//步驟五
final DrawerLayout drawerLayout=(DrawerLayout) findViewById(R.id.drawer_layout);
NavigationView navigationView=(NavigationView) findViewById(R.id.nav_view);
navigationView.setCheckedItem(R.id.call);//將call選單項設定為選中狀態
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {//可以在這里使用switch陳述句區分各個選單項
        drawerLayout.closeDrawers();
        return true;
    }
});

4.懸浮按鈕和可互動提示

4.1FloatingActionButton

該控制元件可以幫助我們很輕松的實作懸浮按鈕的效果,

示例:

<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" />
        
    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab"
        android:src="@drawable/ic_done"
        android:layout_margin="16dp"
        android:layout_gravity="bottom|end"//此處的end同樣也是根據系統語言來自動選擇left或right
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:elevation="8dp"/>//該屬性可以調整懸浮按鈕下的陰影狀態
        
</FrameLayout>

//我們還可以給這個懸浮按鈕注冊一個點擊事件
FloatingActionButton fab=(FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Toast.makeText(MainActivity.this,"ok",Toast.LENGTH_SHORT).show();
    }
});

4.2Snackbar

在此之前我們向用戶發送提示資訊時最常用的便是Toast了,但是Toast僅僅只能通知用戶一些簡單的資訊,而用戶則只能被動接收,因為沒有什么辦法能讓用戶來進行選擇,

現在讓我們設想一個場景當用戶在洗掉檔案時,如果不小心洗掉了幾個重要的檔案,假設我們只是用Toas來提示用戶而沒有給出取消的方法時,相信用戶肯定會抓狂吧,而Snackbar則可以很好的解決這個問題,

示例:

fab.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Snackbar.make(view,"you delete some import data",Snackbar.LENGTH_SHORT).setAction("Undo", new View.OnClickListener() {//setAction()方法的第一個引數是按鈕名,第二個是監聽器
            @Override
            public void onClick(View view) {a
                Toast.makeText(MainActivity.this,"Data restored",Toast.LENGTH_SHORT).show();
            }
        }).show();
    }
});

4.3CoordinatorLayout

如果你已經運行了我們在上面講的代碼的話,那你一定會發現Snackbar的提示資訊將我們的懸浮按鈕給遮擋住了,這樣是十分影響界面的美觀的,而我們本節要講的CoordinatorLayout就可以解決這個問題了,

CoordinatorLayout是一個升級版的FrameLayout,它可以監聽其所有子控制元件的各種事件,然后幫助我們做出最為合理的回應,

示例:

<androidx.coordinatorlayout.widget.CoordinatorLayout
    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" />
        
    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab"
        android:src="@drawable/ic_done"
        android:layout_margin="16dp"
        android:layout_gravity="bottom|end"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:elevation="8dp"/>
        
</androidx.coordinatorlayout.widget.CoordinatorLayout>

5.卡片式布局

5.1CardView

卡片式布局中的所有控制元件都將被放置在一張卡片上,給人一種立體的感覺,接下來我們就用RecyclerView來展示卡片布局的特點,

示例:

//主活動布局
<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/recycler_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
//RecyclerView子項布局
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_margin="5dp"
    app:cardCornerRadius="4dp"//該屬性用來指定卡片布局圓角的弧度
    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:src="@drawable/orange"
            android:scaleType="centerCrop"//該屬性表示以同步的比例對圖片進行縮放
            android:layout_width="match_parent"
            android:layout_height="100dp" />

        <TextView
            android:id="@+id/fruit_name"
            android:text="orange"
            android:textSize="16sp"
            android:layout_margin="5dp"
            android:layout_gravity="center"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

    </LinearLayout>

</androidx.cardview.widget.CardView>
//子項的類
public class Fruit {
    private String name;
    private int image;
    
    public Fruit(String name,int image){
        this.image=image;
        this.name=name;
    }

    public String getName() {
        return name;
    }

    public int getImage() {
        return image;
    }
}
//RecyclerView的配接器
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {

    private List<Fruit> mList;

    public MyAdapter(List<Fruit> list){
        mList=list;
    }

    public class ViewHolder extends RecyclerView.ViewHolder{
        TextView name;
        ImageView image;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            name=itemView.findViewById(R.id.fruit_name);
            image=itemView.findViewById(R.id.fruit_image);
        }
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout,parent,false);
        ViewHolder viewHolder=new ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Fruit fruit=mList.get(position);
        holder.name.setText(fruit.getName());
        holder.image.setImageResource(fruit.getImage());
    }

    @Override
    public int getItemCount() {
        return mList.size();
    }
}
//主活動
private List<Fruit> list=new ArrayList<>();

initFruits();
RecyclerView recyclerView=(RecyclerView) findViewById(R.id.recycler_view);
GridLayoutManager manager=new GridLayoutManager(this,2);
recyclerView.setLayoutManager(manager);
MyAdapter adapter=new MyAdapter(list);
recyclerView.setAdapter(adapter);

public void initFruits(){
    for(int i=0;i<50;i++){
        Fruit fruit=new Fruit("orange",R.drawable.orange);
        list.add(fruit);
    }
}

5.2AppBarLayout

如果你已經運行過上一節示例中的代碼的話,那么你一定會發現RecyclerView布局將Toolbar標題欄給遮擋住了,這同樣會影響我們界面的美觀,而我們在本節中要學的AppBarLayout就可以解決這個問題了,

AppBarLayout實際上是一個垂直方向上的LinearLayout,不同的是它在內部做了很多滾動事件的封裝,并應用了Material Design的設計理念,

示例:

<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/colorPrimary"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
        app:layout_scrollFlags="scroll|snap|enterAlways"/>
        //該屬性可以使控制元件更好的配合滑動事件,
        //其中scroll表示當recyclerview向上滾動時,Toolbar會跟著一起向上移動并實作隱藏;
		//snap表示當Toolbar還沒有完全隱藏或顯示時,會根據當前的距離自動選擇隱藏還是顯示;
		//enterAlways表示當recyclerview向下滾動時,Toolbar會跟著向下移動并重新顯示,
        
</com.google.android.material.appbar.AppBarLayout>

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/recycler_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"/>//我們這里讓recyclerview向下偏移一個標題欄的長度

6.下拉重繪

我們在日常使用app時,經常會用到下拉重繪這個功能,而在本節中我們就來實作該功能,

示例:

<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
    android:id="@+id/swipe_layout"
    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/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
        
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>

//我們還要在活動中去處理重繪的邏輯
final SwipeRefreshLayout swipeRefreshLayout=(SwipeRefreshLayout) findViewById(R.id.swipe_layout);
swipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary);//設定進度條的顏色
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
    @Override
    public void onRefresh() {
        //重繪的邏輯代碼,此處一般是從網咯中獲取資料,因此會開辟一個執行緒來進行處理,
        swipeRefreshLayout.setRefreshing(false);//重繪完成后,關閉進度條
    }
});

7.可折疊式標題欄

7.1CollapsingToolbarLayout

我們可以利用CollapsingToolbarLayout布局,來幫助我們實作可折疊式的標題欄,不過CollapsingToolbarLayout是不能單獨存在的,它只能作為AppBarLayout的直接子布局來使用,而AppBarLayout又必須是CoordinatorLayout的子布局,接下來我們就來看一個CollapsingToolbarLayout的示例吧,

示例:

//新活動的布局
<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:id="@+id/appBar"
        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="?attr/colorPrimary"//該屬性用于設定當標題欄完全折疊式的背景顏色
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <ImageView
                android:id="@+id/fruit_image_view"
                android:src="@drawable/orange"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:scaleType="centerCrop"
                app:layout_collapseMode="parallax"/>//該屬性表示該控制元件會隨著折疊而折疊

            <androidx.appcompat.widget.Toolbar
                android:id="@+id/toolbar02"
                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.core.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <androidx.cardview.widget.CardView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginTop="35dp"
                android:layout_marginLeft="15dp"
                android:layout_marginRight="15dp"
                android:layout_marginBottom="15dp"
                app:cardCornerRadius="4dp">

                <TextView
                    android:id="@+id/fruit_content_text"
                    android:layout_margin="10dp"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"/>

            </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/ic_comment"
        app:layout_anchor="@id/appBar"//該屬性用于給懸浮按鈕定義一個錨點
        app:layout_anchorGravity="bottom|end" />//該屬性用于設定懸浮按鈕相對于錨點的位置

</androidx.coordinatorlayout.widget.CoordinatorLayout>
//新活動的代碼
public class MainActivity2 extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        Intent intent=getIntent();
        String name=intent.getStringExtra("name");
        int image=intent.getIntExtra("image",-1);
        Toolbar toolbar=(Toolbar) findViewById(R.id.toolbar02);
        CollapsingToolbarLayout collapsingToolbarLayout=(CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
        ImageView fruitImage=(ImageView) findViewById(R.id.fruit_image_view);
        TextView fruitContent=(TextView) findViewById(R.id.fruit_content_text);
        setSupportActionBar(toolbar);
        ActionBar actionBar=getSupportActionBar();
        if(actionBar!=null){
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
        collapsingToolbarLayout.setTitle(name);
        fruitImage.setImageResource(image);
        StringBuilder content=new StringBuilder();
        for(int i=0;i<3000;i++){
            content.append(name);
        }
        fruitContent.setText(content.toString());
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            case android.R.id.home:
                finish();
                break;
            default:
        }
        return super.onOptionsItemSelected(item);
    }
}
//recyclerview的配接器
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {

    private List<Fruit> mList;

    public MyAdapter(List<Fruit> list){
        mList=list;
    }

    public class ViewHolder extends RecyclerView.ViewHolder{
        View view;
        TextView name;
        ImageView image;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            view=itemView;
            name=itemView.findViewById(R.id.fruit_name);
            image=itemView.findViewById(R.id.fruit_image);
        }
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull final ViewGroup parent, int viewType) {
        View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout,parent,false);
        final ViewHolder viewHolder=new ViewHolder(view);
        viewHolder.view.setOnClickListener(new View.OnClickListener() {//設定點擊事件
            @Override
            public void onClick(View view) {
                int position=viewHolder.getAdapterPosition();
                Fruit fruit=mList.get(position);
                Intent intent=new Intent(parent.getContext(),MainActivity2.class);
                intent.putExtra("name",fruit.getName());
                intent.putExtra("image",fruit.getImage());
                parent.getContext().startActivity(intent);//開啟新活動
            }
        });
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Fruit fruit=mList.get(position);
        holder.name.setText(fruit.getName());
        holder.image.setImageResource(fruit.getImage());
    }

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

7.2充分利用系統狀態欄空間

如果你運行了我們上一節中的代碼,那么你一定發現了系統狀態欄哪里感覺與我們的界面非常不搭配,而要解決這一問題也非常簡單,只需把系統狀態欄設定為透明色即可,

示例:

//首先給你要實作融合的控制元件及其父布局都設定上android:fitsSystemWindows="true"屬性
<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"
    android:fitsSystemWindows="true">

    <com.google.android.material.appbar.AppBarLayout
        android:id="@+id/appBar"
        android:layout_width="match_parent"
        android:fitsSystemWindows="true"
        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="?attr/colorPrimary"
            android:fitsSystemWindows="true"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <ImageView
                android:id="@+id/fruit_image_view"
                android:src="@drawable/orange"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:scaleType="centerCrop"
                app:layout_collapseMode="parallax"
                android:fitsSystemWindows="true"/>

            <androidx.appcompat.widget.Toolbar
                android:id="@+id/toolbar02"
                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.core.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <androidx.cardview.widget.CardView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginTop="35dp"
                android:layout_marginLeft="15dp"
                android:layout_marginRight="15dp"
                android:layout_marginBottom="15dp"
                app:cardCornerRadius="4dp">

                <TextView
                    android:id="@+id/fruit_content_text"
                    android:layout_margin="10dp"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"/>

            </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/ic_comment"
        app:layout_anchor="@id/appBar"
        app:layout_anchorGravity="bottom|end" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>

//將系統狀態欄的顏色設定為透明色(因為只有在Android5.0后我們才可以這樣做,因此我們要對此做區分)
//values-v21下的styles檔案
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="FruitActivityTheme" parent="AppTheme">//使其繼承自AppTheme,這樣AppTheme所擁有的特性它也會擁有
        <item name="android:statusBarColor">@android:color/transparent</item>
    </style>
</resources>
//values下的styles檔案
<resources>
    <!-- Base application theme. -->
    <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>

    <style name="FruitActivityTheme" parent="AppTheme">
    </style>

</resources>

//給第二個活動使用我們新建的主題
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.temp">

    <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/AppTheme">
        <activity android:name=".MainActivity2"
            android:theme="@style/FruitActivityTheme" />
        <activity
            android:name=".MainActivity"
            android:label="MyBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/41750.html

標籤:其他

上一篇:canvas繪制星星和月亮

下一篇:android自定義通知欄并通過廣播實作監聽

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • vue移動端上拉加載

    可能做得過于簡單或者比較low,請各位大佬留情,一起探討技術 ......

    uj5u.com 2020-09-10 04:38:07 more
  • 優美網站首頁,頂部多層導航

    一個個人用的瀏覽器首頁,可以把一下常用的網站放在這里,平常打開會比較方便。 第一步,HTML代碼 <script src=https://www.cnblogs.com/szharf/p/"js/jquery-3.4.1.min.js"></script> <div id="navigate"> <ul> <li class="labels labels_1"> ......

    uj5u.com 2020-09-10 04:38:47 more
  • 頁面為要加<!DOCTYPE html>

    最近因為寫一個js函式,需要用到$(window).height(); 由于手寫demo的時候,過于自信,其實對前端方面的認識也不夠體系,用文本檔案直接敲出來的html代碼,第一行沒有加上<!DOCTYPE html> 導致了$(window).height();的結果直接是整個document的高 ......

    uj5u.com 2020-09-10 04:38:52 more
  • WordPress網站程式手動升級要做好資料備份

    WordPress博客網站程式在進行升級前,必須要做好網站資料的備份,這個問題良家佐言是遇見過的;在剛開始接觸WordPress博客程式的時候,因為升級問題和博客網站的修改的一些嘗試,良家佐言是吃盡了苦頭。因為購買的是西部數碼的空間和域名,每當佐言把自己的WordPress博客網站搞到一塌糊涂的時候 ......

    uj5u.com 2020-09-10 04:39:30 more
  • WordPress程式不能升級為5.4.2版本的原因

    WordPress是一款個人博客系統,受到英文博客愛好者和中文博客愛好者的追捧,并逐步演化成一款內容管理系統軟體;它是使用PHP語言和MySQL資料庫開發的,用戶可以在支持PHP和MySQL資料庫的服務器上使用自己的博客。每一次WordPress程式的更新,就會牽動無數WordPress愛好者的心, ......

    uj5u.com 2020-09-10 04:39:49 more
  • 使用CSS3的偽元素進行首字母下沉和首行改變樣式

    網頁中常見的一種效果,首字改變樣式或者首行改變樣式,效果如下圖。 代碼: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, ......

    uj5u.com 2020-09-10 04:40:09 more
  • 關于a標簽的講解

    什么是a標簽? <a> 標簽定義超鏈接,用于從一個頁面鏈接到另一個頁面。 <a> 元素最重要的屬性是 href 屬性,它指定鏈接的目標。 a標簽的語法格式:<a href=https://www.cnblogs.com/summerxbc/p/"指定要跳轉的目標界面的鏈接">需要展示給用戶看見的內容</a> a標簽 在所有瀏覽器中,鏈接的默認外觀如下: 未被訪問的鏈接帶 ......

    uj5u.com 2020-09-10 04:40:11 more
  • 前端輪播圖

    在需要輪播的頁面是引入swiper.min.js和swiper.min.css swiper.min.js地址: 鏈接:https://pan.baidu.com/s/15Uh516YHa4CV3X-RyjEIWw 提取碼:4aks swiper.min.css地址 鏈接:https://pan.b ......

    uj5u.com 2020-09-10 04:40:13 more
  • 如何設定html中的背景圖片(全屏顯示,且不拉伸)

    1 <style>2 body{background-image:url(https://uploadbeta.com/api/pictures/random/?key=BingEverydayWallpaperPicture); 3 background-size:cover;background ......

    uj5u.com 2020-09-10 04:40:16 more
  • Java學習——HTML詳解(上)

    HTML詳解 初識HTML Hyper Text Markup Language(超文本標記語言) 1 <!--DOCTYPE:告訴瀏覽器我們要使用什么規范--> 2 <!DOCTYPE html> 3 <html lang="en"> 4 <head> 5 <!--meta 描述性的標簽,描述一些 ......

    uj5u.com 2020-09-10 04:40:33 more
最新发布
  • 我的第一個NPM包:panghu-planebattle-esm(胖虎飛機大戰)使用說明

    好家伙,我的包終于開發完啦 歡迎使用胖虎的飛機大戰包!! 為你的主頁添加色彩 這是一個有趣的網頁小游戲包,使用canvas和js開發 使用ES6模塊化開發 效果圖如下: (覺得圖片太sb的可以自己改) 代碼已開源!! Git: https://gitee.com/tang-and-han-dynas ......

    uj5u.com 2023-04-20 07:59:23 more
  • 生產事故-走近科學之消失的JWT

    入職多年,面對生產環境,盡管都是小心翼翼,慎之又慎,還是難免捅出簍子。輕則滿頭大汗,面紅耳赤。重則系統停擺,損失資金。每一個生產事故的背后,都是寶貴的經驗和教訓,都是專案成員的血淚史。為了更好地防范和遏制今后的各類事故,特開此專題,長期更新和記錄大大小小的各類事故。有些是親身經歷,有些是經人耳傳口授 ......

    uj5u.com 2023-04-18 07:55:04 more
  • 記錄--Canvas實作打飛字游戲

    這里給大家分享我在網上總結出來的一些知識,希望對大家有所幫助 打開游戲界面,看到一個畫面簡潔、卻又富有挑戰性的游戲。螢屏上,有一個白色的矩形框,里面不斷下落著各種單詞,而我需要迅速地輸入這些單詞。如果我輸入的單詞與螢屏上的單詞匹配,那么我就可以獲得得分;如果我輸入的單詞錯誤或者時間過長,那么我就會輸 ......

    uj5u.com 2023-04-04 08:35:30 more
  • 了解 HTTP 看這一篇就夠

    在學習網路之前,了解它的歷史能夠幫助我們明白為何它會發展為如今這個樣子,引發探究網路的興趣。下面的這張圖片就展示了“互聯網”誕生至今的發展歷程。 ......

    uj5u.com 2023-03-16 11:00:15 more
  • 藍牙-低功耗中心設備

    //11.開啟藍牙配接器 openBluetoothAdapter //21.開始搜索藍牙設備 startBluetoothDevicesDiscovery //31.開啟監聽搜索藍牙設備 onBluetoothDeviceFound //30.停止監聽搜索藍牙設備 offBluetoothDevi ......

    uj5u.com 2023-03-15 09:06:45 more
  • canvas畫板(滑鼠和觸摸)

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>canves</title> <style> #canvas { cursor:url(../images/pen.png),crosshair; } #canvasdiv{ bo ......

    uj5u.com 2023-02-15 08:56:31 more
  • 手機端H5 實作自定義拍照界面

    手機端 H5 實作自定義拍照界面也可以使用 MediaDevices API 和 <video> 標簽來實作,和在桌面端做法基本一致。 首先,使用 MediaDevices.getUserMedia() 方法獲取攝像頭媒體流,并將其傳遞給 <video> 標簽進行渲染。 接著,使用 HTML 的 < ......

    uj5u.com 2023-01-12 07:58:22 more
  • 記錄--短視頻滑動播放在 H5 下的實作

    這里給大家分享我在網上總結出來的一些知識,希望對大家有所幫助 短視頻已經無數不在了,但是主體還是使用 app 來承載的。本文講述 H5 如何實作 app 的視頻滑動體驗。 無聲勝有聲,一圖頂百辯,且看下圖: 網址鏈接(需在微信或者手Q中瀏覽) 從上圖可以看到,我們主要實作的功能也是本文要講解的有: ......

    uj5u.com 2023-01-04 07:29:05 more
  • 一文讀懂 HTTP/1 HTTP/2 HTTP/3

    從 1989 年萬維網(www)誕生,HTTP(HyperText Transfer Protocol)經歷了眾多版本迭代,WebSocket 也在期間萌芽。1991 年 HTTP0.9 被發明。1996 年出現了 HTTP1.0。2015 年 HTTP2 正式發布。2020 年 HTTP3 或能正... ......

    uj5u.com 2022-12-24 06:56:02 more
  • 【HTML基礎篇002】HTML之form表單超詳解

    ??一、form表單是什么

    ??二、form表單的屬性

    ??三、input中的各種Type屬性值

    ??四、標簽 ......

    uj5u.com 2022-12-18 07:17:06 more