fragment学习和使用

所花时间(包括上课):

 4h

代码量(行):

 300左右

搏客量(篇):

 1

了解到的知识点:

fragment

备注(其他):

 

这里先介绍以下Fragment的两种创建方式:静态创建和动态创建

静态创建和动态创建的生命周期:

静态创建是先创建一个fragment,在创建activity

动态创建是先创建一个activity,在创建一个fragment

 

 

一、静态创建

 

 

 源码如下:

fragment文件

复制代码
复制代码
package com.example.fragment.fragment;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.fragment.R;


public class StaticFragment1 extends Fragment {


    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;
    private TextView tvlike;
    private RadioButton rblike, rbDislike;
    private RatingBar rbstar;

    public StaticFragment1() {
        // 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 StaticFragment1.
     */
    // TODO: Rename and change types and number of parameters
    public static StaticFragment1 newInstance(String param1, String param2) {
        StaticFragment1 fragment = new StaticFragment1();
        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_static1, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        rblike = view.findViewById(R.id.rb_like);
        rbDislike = view.findViewById(R.id.rb_dislike);
        tvlike = view.findViewById(R.id.tv_like);
        rbstar = view.findViewById(R.id.rb_star);
        rblike.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    tvlike.setText("app喜欢");
                }
            }
        });
        rbDislike.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    tvlike.setText("app不喜欢");
                }
            }
        });
        rbstar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
            @Override
            public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
                if (fromUser) {
                    Toast.makeText(getActivity(), "点了" + rating, Toast.LENGTH_SHORT).show();
                }
            }
        });


    }

}
复制代码
复制代码

java文件

复制代码
复制代码
package com.example.fragment;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

public class StaticFragmentActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_static_framgent);
    }
}
复制代码
复制代码

1.xml

复制代码
复制代码
<?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="wrap_content"
    tools:context=".fragment.StaticFragment1"
    android:orientation="vertical"
    android:background="#748751"
    android:padding="10dp">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:gravity="center_vertical">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="喜欢"
            android:textSize="20sp"
            android:id="@+id/tv_like"
            />
        <RadioGroup
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/rb_like"
                android:text="喜欢" />
            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/rb_dislike"
                android:text="不喜欢" />
        </RadioGroup>

    </LinearLayout>
    <RatingBar
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/rb_star">

    </RatingBar>

</LinearLayout>
复制代码
复制代码

2.xml

复制代码
复制代码
<?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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".StaticFragmentActivity">
<fragment
    android:layout_margin="10dp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:layout="@layout/fragment_static1 "
    android:name="com.example.fragment.fragment.StaticFragment1"
    android:id="@+id/fragment"
/>
    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/fragment2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        tools:layout="@layout/fragment_static1 "
        android:name="com.example.fragment.fragment.StaticFragment1"
        />
</LinearLayout>
复制代码
复制代码

实现效果如下:

 

 

 

二、动态创建

 

 

 

源码如下:

fragment文件

复制代码
复制代码
package com.example.fragment.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.fragment.R;


public class ExampleFragment extends Fragment {


  public static final String ARG_PARAM1 = "param1";
   public static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private TextView tvlike,tvcontent;
    private RadioButton rblike, rbDislike;
    private RatingBar rbstar;

    public ExampleFragment() {
        // 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 StaticFragment1.
     */
    // TODO: Rename and change types and number of parameters
    public static ExampleFragment newInstance(String param1, String param2) {
        ExampleFragment fragment = new ExampleFragment();
        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.frangment_example, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        rblike = view.findViewById(R.id.rb_like);
        rbDislike = view.findViewById(R.id.rb_dislike);
        tvlike = view.findViewById(R.id.tv_like);
        rbstar = view.findViewById(R.id.rb_star);
        tvcontent=view.findViewById(R.id.tv_content);
        rblike.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    tvlike.setText("app喜欢");
                }
            }
        });
        rbDislike.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    tvlike.setText("app不喜欢");
                }
            }
        });
        rbstar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
            @Override
            public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
                if (fromUser) {
                    Toast.makeText(getActivity(), "点了" + rating, Toast.LENGTH_SHORT).show();
                }
            }
        });
        tvcontent.setText(mParam1);


    }

}
复制代码
复制代码

java文件

复制代码
复制代码
package com.example.fragment;

import static androidx.fragment.app.FragmentManager.TAG;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.os.Bundle;
import android.util.Log;

import com.example.fragment.fragment.ExampleFragment;

public class DynamicFragmentActivity extends AppCompatActivity {
private static final String TAG="DynamicFragmentActivity";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dynamic_fragment);

        Log.d(TAG,"onCreate:saveInstance"+savedInstanceState);
        if(savedInstanceState==null) //防止多次添加
        {

            FragmentManager fragmentManager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

           Bundle bundle=new Bundle();
           bundle.putString(ExampleFragment.ARG_PARAM1,"这是动态Fragment");
            fragmentTransaction.add(R.id.fcv, ExampleFragment.class, bundle)
                   .setReorderingAllowed(true)//顺序可以更改
                    .commit();
        }
    }
}
复制代码
复制代码

1.xml

复制代码
复制代码
<?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="wrap_content"
    tools:context=".fragment.ExampleFragment"
    android:orientation="vertical"
    android:background="#748751"
    android:padding="10dp">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:gravity="center_vertical">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="喜欢"
            android:textSize="20sp"
            android:id="@+id/tv_like"
            />
        <RadioGroup
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/rb_like"
                android:text="喜欢" />
            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/rb_dislike"
                android:text="不喜欢" />
        </RadioGroup>

    </LinearLayout>
    <RatingBar
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/rb_star">

    </RatingBar>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tv_content"
        android:textSize="25sp"
        />

</LinearLayout>
复制代码
复制代码

2.xml

复制代码
复制代码
<?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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".DynamicFragmentActivity">

    <androidx.fragment.app.FragmentContainerView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/fcv"

        />
</LinearLayout>
复制代码
复制代码

效果展示:

posted @   平安喜乐×  阅读(17)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
· 为什么 退出登录 或 修改密码 无法使 token 失效
点击右上角即可分享
微信分享提示