Activity Fragment 安卓

 


作者:@kuaiquxie
作者的github:https://github.com/bitebita
本文为作者原创,如需转载,请注明出处:https://www.cnblogs.com/dzwj/p/16581787.html


Activity Fragment

 

一个layout 界面,需要一个 activity

一个 activity 可以包含 多个 fragment ,fragment 依赖于 activity,不能单独存在,activity管理fragment

Activity的创建三部曲

新建类继承Activity或其子类

在AndroidManifest中声明

创建layout并在Activity的onCreate中设置

基本属性

设置 APP 的名字
android:label="@string/app_name2"

将上面的 横框 去掉
android:theme="@style/Theme.AppCompat.Light.NoActionBar"

可以设置 横屏 竖屏
android:screenOrientation=""

可以设置 启动模式
android:launchMode=""

默认启动 哪一个 activity 加 intent-filter
<activity
         android:name=".MainActivity"
         android:exported="true">
   <intent-filter>
       <action android:name="android.intent.action.MAIN" />

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

 

activity的生命周期

 

onResume() 重新刷新

onPause() 暂停方法

 

假如,你正在玩游戏,然后来了一个电话,

这时候就会执行onPause() 方法,等你打完电话时,重新进入会执行 onResume() 方法,然后继续执行后面的方法

public class LifeCycleActivity extends AppCompatActivity {

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_life_cycle);
       Log.d("lifecycle","_________________onCreate");
  }

   @Override
   protected void onStart() {
       super.onStart();
       Log.d("lifecycle","_________________onStart");
  }

   @Override
   protected void onRestart() {
       super.onRestart();
       Log.d("lifecycle","_________________onRestart");
  }

   @Override
   protected void onResume() {
       super.onResume();
       Log.d("lifecycle","_________________onResume");
  }

   @Override
   protected void onPause() {
       super.onPause();
       Log.d("lifecycle","_________________onPause");
  }

   @Override
   protected void onStop() {
       super.onStop();
       Log.d("lifecycle","_________________onStop");
  }

   @Override
   protected void onDestroy() {
       super.onDestroy();
       Log.d("lifecycle","_________________onDestroy");
  }
}

 

Activity的跳转和数据传递

显式跳转和隐式跳转

Activity之间的数据传递

startActivityForResult :启动Activity,结束后返回结果

 

隐式跳转

public class AActivity extends AppCompatActivity {

   private Button mBtnJump;

   @Override
   protected void onCreate(@Nullable Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_a);

       mBtnJump = findViewById(R.id.jump);
       mBtnJump.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {
/*//       显式跳转
               Intent intent= new Intent(AActivity.this,BActivity.class);
               startActivity(intent);*/

//               隐式跳转
               Intent intent= new Intent();
               intent.setAction("com.jing.study01.jump.BActivity");
               startActivity(intent);

          }
      });

数据传递 A 到 B

AActivity 传入数据,BActivity 接收数据

public class AActivity extends AppCompatActivity {

   private Button mBtnJump;

   @Override
   protected void onCreate(@Nullable Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_a);

       mBtnJump = findViewById(R.id.jump);
       mBtnJump.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {
//               显式跳转
               Intent intent= new Intent(AActivity.this,BActivity.class);

//               数据传递,数据传入,添加数据
               Bundle bundle= new Bundle();
//               加入数据
               bundle.putString("name","jing");
               bundle.putInt("num",89);
               intent.putExtras(bundle);

               startActivity(intent);

          }
      });


  }
}

 

public class BActivity extends AppCompatActivity {

   private TextView mTvTitle;

   @Override
   protected void onCreate(@Nullable Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_b);

       mTvTitle = findViewById(R.id.tv_title);

//       数据传递,获取数据
//       getExtras() 返回的是一个 bundle
       Bundle bundle = getIntent().getExtras();
       String name = bundle.getString("name");
       int num = bundle.getInt("num");

       mTvTitle.setText(name+","+num);

  }
}

 

数据回传

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical">
   
   <Button
       android:id="@+id/jump"
       android:layout_width="wrap_content"
       android:layout_height="50dp"
       android:text="jump"/>

</LinearLayout>

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical">

   <TextView
       android:id="@+id/tv_title"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"

       android:textColor="#000"
       android:textSize="20sp"
       />

   <Button
       android:id="@+id/finish"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:text="finish"
       />

</LinearLayout>

 

public class AActivity extends AppCompatActivity {

   private Button mBtnJump;

   @Override
   protected void onCreate(@Nullable Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_a);

       mBtnJump = findViewById(R.id.jump);
       mBtnJump.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {
//               显式跳转
               Intent intent= new Intent(AActivity.this,BActivity.class);

//               数据传递,数据传入,添加数据
               Bundle bundle= new Bundle();
//               加入数据
               bundle.putString("name","jing");
               bundle.putInt("num",89);
               intent.putExtras(bundle);

//               startActivity(intent);
//               请求码就是 BActivity 传递过来的数据,如果有多个 BActivity,就设置不同的请求码
               startActivityForResult(intent,0);
          }
      });

  }

//   requestCode 就是 上面的那个 requestCode
//
   @Override
   protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
       super.onActivityResult(requestCode, resultCode, data);
       Toast.makeText(AActivity.this, data.getExtras().getString("title"), Toast.LENGTH_LONG).show();
  }
}

 

public class BActivity extends AppCompatActivity {

   private TextView mTvTitle;
   private Button mBtnFinish;

   @Override
   protected void onCreate(@Nullable Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_b);

       mTvTitle = findViewById(R.id.tv_title);
       mBtnFinish = findViewById(R.id.finish);

//       数据传递,获取数据
//       getExtras() 返回的是一个 bundle
       Bundle bundle = getIntent().getExtras();
       String name = bundle.getString("name");
       int num = bundle.getInt("num");
       mTvTitle.setText(name+","+num);

       mBtnFinish.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {
               Intent intent= new Intent();
//               写入数据
               Bundle bundle1= new Bundle();
               bundle1.putString("title","回调成功");
               intent.putExtras(bundle1);

               setResult(Activity.RESULT_OK,intent);
//               finish()方法呢,就是 点击按钮,关闭当前界面
//               关闭前 回传 一个数据
               finish();

          }
      });


  }
}

 

Activity 的四种启动模式

 

 

 

Fragment

 

Fragment 1

 

 

 

 Fragment有自己的生命周期

 Fragment依赖于Activity【当Activity销毁的时候Fragment会同步被销毁】

 Fragment通过getActivity()可以获取所在的Activity;Activity通过FragmentManager的findFragmentById()或findFragmentByTag()获取Fragment

 Fragment和Activity是多对多的关系【一个Fragment可以存在于多个Activity当中,可以被多个Activity所包含,多个Fragment也可以在一个Activity当中】

 

fragment 传参取参,显示界面

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 view) {

               if (bFragment == null){
                   bFragment = new BFragment();
              }
               getSupportFragmentManager().beginTransaction().replace(R.id.fl_container,bFragment).commitAllowingStateLoss();
          }
      });

//       实例化AFragment
        aFragment= AFragment.newInstance("我是参数");
//       把AFragment 添加到 Activity 中指定的位置去
//       使用 commitAllowingStateLoss() 可以容忍一些错误
       getSupportFragmentManager().beginTransaction().add(R.id.fl_container,aFragment).commitAllowingStateLoss();

  }
}

 

public class AFragment extends Fragment {

   private TextView mTvTitle;

   public static AFragment newInstance(String title){
       AFragment aFragment= new AFragment();
       Bundle bundle= new Bundle();
//       加入数据
       bundle.putString("title",title);
       aFragment.setArguments(bundle);

       return aFragment;

  }

   @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 (getArguments() != null){
           mTvTitle.setText(getArguments().getString("title"));
      }


  }
}

 

<?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="wrap_content"
       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">

   </FrameLayout>

</RelativeLayout>

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
   android:gravity="center">

   <TextView
       android:id="@+id/tv_title"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:text="我是AFragment"
       android:textSize="20sp"
       android:gravity="center"
       />

</LinearLayout>

 

 

fragment 回退栈

public class AFragment extends Fragment {

   private TextView mTvTitle;
   private Button mBtnChange,mBtnReset;
   private BFragment bFragment;

   public static AFragment newInstance(String title){
       AFragment aFragment= new AFragment();
       Bundle bundle= new Bundle();
//       加入数据
       bundle.putString("title",title);
       aFragment.setArguments(bundle);

       return aFragment;
  }

   @Nullable
   @Override
   public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

//       将布局传入
       View view = inflater.inflate(R.layout.fragment_a,container,false);
       Log.d("AFragment","_________onCreateView______________");
       return view;
  }

   @Override
   public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
       super.onViewCreated(view, savedInstanceState);

       mTvTitle = view.findViewById(R.id.tv_title);
       mBtnChange = view .findViewById(R.id.btn_change);
       mBtnReset = view.findViewById(R.id.btn_reset);

       mBtnChange.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {

               if (bFragment == null){
                   bFragment = new BFragment();
              }
               Fragment fragment = getFragmentManager().findFragmentByTag("a");
               if (fragment != null){
                   getFragmentManager().beginTransaction().hide(fragment).add(R.id.fl_container,bFragment).addToBackStack(null).commitAllowingStateLoss();
              }else{
                   getFragmentManager().beginTransaction().replace(R.id.fl_container,bFragment).addToBackStack(null).commitAllowingStateLoss();
              }
          }
      });

       mBtnReset.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {
               mTvTitle.setText("我是重新设定的");
          }
      });

       if (getArguments() != null){
           mTvTitle.setText(getArguments().getString("title"));
      }


  }


}

 

public class ContainerActivity extends AppCompatActivity {

   private AFragment aFragment;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_container);
       
//       实例化AFragment
        aFragment= AFragment.newInstance("我是参数");
//       把AFragment 添加到 Activity 中指定的位置去
//       使用 commitAllowingStateLoss() 可以容忍一些错误
       getSupportFragmentManager().beginTransaction().add(R.id.fl_container,aFragment,"a").commitAllowingStateLoss();

  }
}

 

fragment 与 activity 的通信

 

两种方式:

1.普通方法:fragment中按钮点击传递给activity 参数,activity中通过 普通方法 改变 原有的 文本内容

2.activity 实现接口:fragment 里面写一个接口,activity实现该接口,

fragment中按钮点击传递给activity 参数,activity中通过 重写的方法 改变 原有的 文本内容

public class AFragment extends Fragment {

   private TextView mTvTitle;
   private Button mBtnChange,mBtnReset,mBtnMessage;
   private BFragment bFragment;
   private IOnMessageClick iOnMessageClickListener;

   public interface IOnMessageClick{
       void onClick(String text);
  }

   @Override
   public void onAttach(@NonNull Context context) {
       super.onAttach(context);
       try {
           iOnMessageClickListener = (IOnMessageClick) context;
      }catch (ClassCastException e){
           throw new ClassCastException("activity 没有实现 IOnMessageClick接口");
      }
  }

   public static AFragment newInstance(String title){
       AFragment aFragment= new AFragment();
       Bundle bundle= new Bundle();
//       加入数据
       bundle.putString("title",title);
       aFragment.setArguments(bundle);

       return aFragment;
  }

   @Nullable
   @Override
   public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

//       将布局传入
       View view = inflater.inflate(R.layout.fragment_a,container,false);
       Log.d("AFragment","_________onCreateView______________");
       return view;
  }

   @Override
   public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
       super.onViewCreated(view, savedInstanceState);

       mTvTitle = view.findViewById(R.id.tv_title);
       mBtnChange = view .findViewById(R.id.btn_change);
       mBtnReset = view.findViewById(R.id.btn_reset);
       mBtnMessage = view.findViewById(R.id.btn_message);

       mBtnMessage.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {
//               ((ContainerActivity)getActivity()).setData("你好");
                   iOnMessageClickListener.onClick("你好");
          }
      });

       mBtnChange.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {

               if (bFragment == null){
                   bFragment = new BFragment();
              }
               Fragment fragment = getFragmentManager().findFragmentByTag("a");
               if (fragment != null){
                   getFragmentManager().beginTransaction().hide(fragment).add(R.id.fl_container,bFragment).addToBackStack(null).commitAllowingStateLoss();
              }else{
                   getFragmentManager().beginTransaction().replace(R.id.fl_container,bFragment).addToBackStack(null).commitAllowingStateLoss();
              }
          }
      });

       mBtnReset.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {
               mTvTitle.setText("我是重新设定的");
          }
      });

       if (getArguments() != null){
           mTvTitle.setText(getArguments().getString("title"));
      }


  }


}

 

public class ContainerActivity extends AppCompatActivity implements AFragment.IOnMessageClick {

   private AFragment aFragment;
   private TextView mTvtitle;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_container);

       mTvtitle = findViewById(R.id.tv_title);

//       实例化AFragment
        aFragment= AFragment.newInstance("我是参数");
//       把AFragment 添加到 Activity 中指定的位置去
//       使用 commitAllowingStateLoss() 可以容忍一些错误
       getSupportFragmentManager().beginTransaction().add(R.id.fl_container,aFragment,"a").commitAllowingStateLoss();

  }

//   activity里面写 底层方法,让 fragment 去执行方法
   public void setData(String text){
       mTvtitle.setText(text);
  }

   @Override
   public void onClick(String text) {
       mTvtitle.setText(text);
  }
}
 
posted @   kuaiquxie  阅读(21)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示