欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Android学习笔记(Android Studio) 4-2-1~2 Fragment详解(一、二)(不可不会的Activity和Fragment)

程序员文章站 2023-12-31 15:52:52
...

Android学习笔记4-2-1~4-2-2


推荐新手向学习视频:B站https://www.bilibili.com/video/av38409964点我传送


4-2-1 Fragment详解(一)

  • Fragment有自己的生命周期
  • Fragment依赖于Activity
  • Fragment通过getActivity()可以获取所在的Activity;Activity通过FragmentManager的findFragmentById()或findFragmentByTag()获取Fragment
  • Fragment和Activity是多对多的关系

4-2-1 Fragment详解(二)

  • Fragment中getActivity()为null的问题
  • 向Fragment传递参数

(一)(二)代码示例

  • fragment_a.xml

      <?xml version="1.0" encoding="utf-8"?>
      <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:orientation="vertical" 
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:gravity="center">
          <TextView
              android:id="@+id/tv_title"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:textColor="#000"
              android:textSize="20sp"
              android:text="我是AFragment"
              android:gravity="center"/>
          
      </LinearLayout>
    
  • 效果
    Android学习笔记(Android Studio) 4-2-1~2 Fragment详解(一、二)(不可不会的Activity和Fragment)

  • AFragment.java

      package com.ylw.helloworld.fragment;
      
      import android.app.Activity;
      import android.content.Context;
      import android.os.Bundle;
      import android.view.LayoutInflater;
      import android.view.View;
      import android.view.ViewGroup;
      import android.widget.TextView;
      
      import androidx.annotation.NonNull;
      import androidx.annotation.Nullable;
      import androidx.fragment.app.Fragment;
      
      import com.ylw.helloworld.R;
      
      public class AFragment extends Fragment {
      
          private TextView mTvTitle;
      //    private Activity mActivity;
      
          //向Fragment传递参数
          public static AFragment newInstance(String title){
              AFragment fragment = new AFragment();
              Bundle bundle = new Bundle();
              bundle.putString("title",title);
              fragment.setArguments(bundle);
              return fragment;
          }
      
          //设置布局文件
          @Nullable
          @Override
          public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
              View view = inflater.inflate(R.layout.fragment_a,container,false);
              return view;
          }
      
          //当布局文件创建完成后进行查找、调用等
          @Override
          public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
              super.onViewCreated(view, savedInstanceState);
              //
              mTvTitle = view.findViewById(R.id.tv_title);
      //        if (getActivity() != null){   //如果getActivity()为null的问题
      //            //
      //        }else{
      //            //
      //        }
              if (getArguments()!=null){  //向Fragment传递参数
                  mTvTitle.setText(getArguments().getString("title"));
              }
      
          }
      
          @Override
          public void onAttach(Context context) { //与Activity重新保持关系
              super.onAttach(context);
      //        mActivity = (Activity) context;   //如果getActivity()为null的问题
          }
      
          @Override
          public void onDetach() {    //运行该方法会与Activity脱离关系
              super.onDetach();
              //取消异步
          }
      }
    
  • fragment_b.xml

      <?xml version="1.0" encoding="utf-8"?>
      <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:orientation="vertical" 
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:gravity="center">
          <TextView
              android:id="@+id/tv_title"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:textColor="#000"
              android:textSize="20sp"
              android:text="我是BFragment"
              android:gravity="center"/>
          
      </LinearLayout>
    
  • 效果
    Android学习笔记(Android Studio) 4-2-1~2 Fragment详解(一、二)(不可不会的Activity和Fragment)

  • BFragment.java

      package com.ylw.helloworld.fragment;
      
      import android.os.Bundle;
      import android.view.LayoutInflater;
      import android.view.View;
      import android.view.ViewGroup;
      import android.widget.TextView;
      
      import androidx.annotation.NonNull;
      import androidx.annotation.Nullable;
      import androidx.fragment.app.Fragment;
      
      import com.ylw.helloworld.R;
      
      public class BFragment extends Fragment {
      
          private TextView mTvTitle;
      
          //设置布局文件
          @Nullable
          @Override
          public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
              View view = inflater.inflate(R.layout.fragment_b,container,false);
              return view;
          }
      
          //当布局文件创建完成后进行查找、调用等
          @Override
          public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
              super.onViewCreated(view, savedInstanceState);
              //
              mTvTitle = view.findViewById(R.id.tv_title);
          }
      }
    
  • activity_container.xml

      <?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="match_parent">
      
          <Button
              android:id="@+id/btn_change"
              android:layout_width="match_parent"
              android:layout_height="50dp"
              android:text="更换Fragment"/>
      
          <FrameLayout
              android:id="@+id/fl_container"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:layout_below="@+id/btn_change"
              />
      
      </RelativeLayout>
    
  • 效果
    Android学习笔记(Android Studio) 4-2-1~2 Fragment详解(一、二)(不可不会的Activity和Fragment)

  • ContainerActivity.java

      package com.ylw.helloworld.fragment;
      
      import androidx.appcompat.app.AppCompatActivity;
      
      import android.os.Bundle;
      import android.view.View;
      import android.widget.Button;
      
      import com.ylw.helloworld.R;
      
      public class ContainerActivity extends AppCompatActivity {
      
          private AFragment aFragment;
          private BFragment bFragment;
          private Button mBtnChange;
      
          @Override
          protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_container);
              mBtnChange = findViewById(R.id.btn_change);
              mBtnChange.setOnClickListener(new View.OnClickListener() {
                  @Override
                  public void onClick(View v) {
                      if (bFragment == null) {
                          bFragment = new BFragment();
                      }
                      getSupportFragmentManager().beginTransaction().replace(R.id.fl_container,bFragment).commitAllowingStateLoss();
                  }
              });
      
              //实例化AFragment
              //aFragment = new AFragment();
              aFragment = AFragment.newInstance("我是参数");//向Fragment传递参数
              //把AFragment添加到Activity中,记得调用commit/commitAllowingStateLoss,后者可以少一些错误
              getSupportFragmentManager().beginTransaction().add(R.id.fl_container,aFragment).commitAllowingStateLoss();
          }
      }
    
  • 效果
    Android学习笔记(Android Studio) 4-2-1~2 Fragment详解(一、二)(不可不会的Activity和Fragment)

上一篇:

下一篇: