当前位置:网站首页>Fragment 和 CardView

Fragment 和 CardView

2022-08-11 05:22:00 hqhe260

CardView

CardView的基本使用

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

常用API:

cardBackgroundColor   设置背景颜色

cardCornerRadius  设置圆角边大小

cardElevation  阴影大小- 设置为0代表没有阴影

contentPadding  内边距

contentPaddingBottom 底部边距

contentPaddingLeft 左侧边距

contentPaddingRight 右侧边距

contentPaddingTop 顶部边距

<?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_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    app:cardCornerRadius="4dp">
 
    <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>
 
</androidx.cardview.widget.CardView>

MainActivity

package com.example.mycardview;
 
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
 
import android.os.Bundle;
 
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
 
public class MainActivity extends AppCompatActivity {
    private Fruit[] fruits = {new Fruit("Apple", R.drawable.apple), new Fruit("Banana", R.drawable.banana),
            new Fruit("Orange", R.drawable.orange), new Fruit("Watermelon", R.drawable.watermelon),
            new Fruit("Pear", R.drawable.pear), new Fruit("Grape", R.drawable.grape),
            new Fruit("Pineapple", R.drawable.pineapple), new Fruit("Strawberry", R.drawable.strawberry),
            new Fruit("Cherry", R.drawable.cherry), new Fruit("Mango", R.drawable.mango)};
    private List<Fruit> fruitList = new ArrayList<>();
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initFruits();
        RecyclerView rl = findViewById(R.id.rl);
        GridLayoutManager layoutManager = new GridLayoutManager(this, 2);
        rl.setLayoutManager(layoutManager);
        FruitAdapter adapter = new FruitAdapter(fruitList);
        rl.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]);
        }
    }

}

MainActivity.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
 
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rl"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />
 
</androidx.constraintlayout.widget.ConstraintLayout>

adapter


package com.example.mycardview;
 
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
 
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
 
import com.bumptech.glide.Glide;
 
import java.util.List;
 
public class FruitAdapter extends RecyclerView.Adapter<FruitAdapter.ViewHolder> {
 
    private static final String TAG = "FruitAdapter";
 
    private Context mContext;
 
    private List<Fruit> mFruitList;
 
    static class ViewHolder extends RecyclerView.ViewHolder {
        CardView cardView;
        ImageView fruitImage;
        TextView fruitName;
 
        public ViewHolder(View view) {
            super(view);
            cardView = (CardView) view;
            fruitImage = (ImageView) view.findViewById(R.id.fruit_image);
            fruitName = (TextView) view.findViewById(R.id.fruit_name);
        }
    }
 
    public FruitAdapter(List<Fruit> fruitList) {
        mFruitList = fruitList;
    }
 
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (mContext == null) {
            mContext = parent.getContext();
        }
        View view = LayoutInflater.from(mContext).inflate(R.layout.fruit_item, parent, false);
        final ViewHolder holder = new ViewHolder(view);
        return holder;
    }
 
    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        Fruit fruit = mFruitList.get(position);
        holder.fruitName.setText(fruit.getName());
        Glide.with(mContext).load(fruit.getImageId()).into(holder.fruitImage);
    }
 
    @Override
    public int getItemCount() {
        return mFruitList.size();
    }
 
}

实体类


 
package com.example.mycardview;
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;
    }
 

Fragment

Fragment的简介

Fragment译为“碎片”,是Android 3.0(API 11)提出的,最开始是为了适配大屏的平板。

Fragment看起来和Activity一样,是一个用户界面。可以结合多个Fragments到一个activity中来构 建一个有多方面功能的UI,还可以重用同一个Fragment在多个activities中。 Fragment可以当成是

activity的一个组件,每个Fragment有单独的生命周期,可以在activity运行时进行添加和移除

Fragment。因此,相比较于activity, Fragment更加轻量级,更加灵活。 一个Fragment总是被植入在一个activity中 ,并且其生命周期受其父activity直接影响,比如

activity处于暂停,则其中的Fragment都暂停; activity销毁,则所有Fragment都销毁。但是,当

ve rsi on=" 1 . 0" encodi ng=" utf-8" ?>

xml ns : and roi d=" http : //schemas . and roi d . com/apk/res/and roi d"

   xml ns : app=" http : //schemas . and roi d . com/apk/res-auto"

   xml ns : tool s=" http : //schemas . and roi d . com/tool s "

   and roi d : l ayout_wi dth="match_parent"

   and roi d : l ayout_hei ght="match_parent"

   tool s : context=" . Mai nActi vi ty3 ">

   

       and roi d : i d="@+i d/textVi ew"

       and roi d : l ayout_wi dth="match_parent"

       and roi d : l ayout_hei ght="match_parent"

       and roi d : text="主界面" />

   

       and roi d : i d="@+i d/textVi ew2 "

       and roi d : l ayout_g ravi ty=" start"

       and roi d : l ayout_wi dth="match_parent"

       and roi d : l ayout_hei ght="match_parent"

       and roi d : text="滑出页面"

       and roi d : backg round="#fff"/>

一个activity运行时,你可以独立的操作每一个Fragment,比如添加和删除他们。进行类似的操作 时,可以将Fragment添加入被activity管理的后退栈中,这样用户可以通过点击返回按钮来返回之 前打开的Fragment。

Fragment可以作为activity的一部分添加到布局文件中,通过声明元素作为ViewGroup的一部分。 也可以将Fragment作为一个没有自己UI的不可见的activity的工人。

总结一下:

1 . Fragment是依赖于Activity的,不能独立存在。

2. 一个Activity里可以有多个Fragment。

3. 一个Fragment可以被多个Activity重用。

4. Fragment有自己的生命周期,并能接收输入事件。

5. 可以在Activity运行时动态地添加或删除Fragment。

Fragment生命周期

常见的周期流程

1 . Activity加载Fragment的时候,依次调用: onAttach() -> onCreate() -> onCreateView() -> onActivityCreated() -> onStart() ->onResume()

2. 当做出一个悬浮的对话框风格的Activity,或者其他,就是让Fragment所在的Activity可见,但不获 得焦点: onPause()

3. 当对话框关闭, Activity又获得了焦点: onResume()

4. 当替换Fragment,并调用addToBackStack()将它添加到Back栈中: onPause() -> onStop() -> onDestoryView() 。注意,此时的Fragment还没有被销毁哦。

5. 当按下键盘的回退键, Fragment会再次显示出来: onCreateView() -> onActivityCreated() -> onStart() -> onResume() 6. 如果替换后,在事务commit之前没有调用addToBackStack()方法将Fragment添加到back栈中, 或者退出了Activity的话,那么Fragment将会被完全结束, Fragment会进入销毁状态: onPause() -> onStop() -> onDestoryView() -> onDestory() -> onDetach()

Fragment的静态加载

静态加载--以标签的形式添加到Activity的布局当中。

fragment_footer.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"   
 android:layout_width="match_parent"   
 android:layout_height="match_parent"   
 tools:context=".fragment.FooterFragment">

<TextView      
  android:id="@+id/tv_footer"      
  android:layout_width="match_parent"      
  android:layout_height="80dp"      
  android:background="#83A8C5"       
 android:gravity="center"      
  android:textSize="24dp"     
   android:text="页尾" />

FooterFragment

package com.hopu.myapplication82fragment.Fragment;

import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

import com.hopu.myapplication82fragment.R;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link FooterFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class FooterFragment extends Fragment {
private Button button,button2,button3,button4,button5;
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public FooterFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment FooterFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static FooterFragment newInstance(String param1, String param2) {
        FooterFragment fragment = new FooterFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view=inflater.inflate(R.layout.fragment_footer, container, false);
        button=view.findViewById(R.id.button);
        button2=view.findViewById(R.id.button2);
        button3=view.findViewById(R.id.button3);
        button4=view.findViewById(R.id.button4);
        button5=view.findViewById(R.id.button5);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(getActivity(), "button正在被点击", Toast.LENGTH_SHORT).show();
            }
        });


        return view;
    }
}

Fragment的静态加载

xml文件

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ff62"
    tools:context=".Fragment.Fragment1">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_gravity="center"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="第一个碎片" />

</FrameLayout>

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#7B3B97"
    tools:context=".Fragment.Fragment2">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="第二个碎片" />

</FrameLayout>
package com.hopu.myapplication82fragment.Fragment;

import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.hopu.myapplication82fragment.R;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link Fragment1#newInstance} factory method to
 * create an instance of this fragment.
 */
public class Fragment1 extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public Fragment1() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment Fragment1.
     */
    // TODO: Rename and change types and number of parameters
    public static Fragment1 newInstance(String param1, String param2) {
        Fragment1 fragment = new Fragment1();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_1, container, false);
    }
}




package com.hopu.myapplication82fragment.Fragment;

import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.hopu.myapplication82fragment.R;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link Fragment2#newInstance} factory method to
 * create an instance of this fragment.
 */
public class Fragment2 extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public Fragment2() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment Fragment2.
     */
    // TODO: Rename and change types and number of parameters
    public static Fragment2 newInstance(String param1, String param2) {
        Fragment2 fragment = new Fragment2();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_2, container, false);
    }
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    tools:context=".MainActivity2">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/button6"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="第一个碎片" />

        <Button
            android:id="@+id/button7"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="第二个碎片" />
    </LinearLayout>

    <FrameLayout
        android:id="@+id/fl_dl"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </FrameLayout>
</LinearLayout>
package com.hopu.myapplication82fragment;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import com.hopu.myapplication82fragment.Fragment.Fragment1;
import com.hopu.myapplication82fragment.Fragment.Fragment2;

public class MainActivity2 extends AppCompatActivity {
private Button button6,button7;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        button6=  findViewById(R.id.button6);
        button7=  findViewById(R.id.button7);


        button6.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Fragment1 fragment1=new Fragment1();
                getSupportFragmentManager().beginTransaction().replace(R.id.fl_dl,fragment1).commit();
            }
        });

        button7.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Fragment2 fragment2=new Fragment2();
                getSupportFragmentManager().beginTransaction().replace(R.id.fl_dl,fragment2).commit();
            }
        });
    }
}

3. 创建Fragment1   创建Fragment2

4.. 在活动中,点击按钮后切换Fragment

原网站

版权声明
本文为[hqhe260]所创,转载请带上原文链接,感谢
https://blog.csdn.net/heqiang260/article/details/126184027