Fragment使用为什么要开启事务?Fragment怎么进行查找?

1. 前言

今天在面试顺丰的时候遇到了这两个问题。平时确实没有注意过这两个问题,这里记录下。另外面试过程了解到顺丰偏向于跨平台开发,不太偏向Android原生开发。所以在面试过程中还问了前端的知识,比如为什么使用虚拟DomVue的渲染过程等。

  • Fragment怎么进行查找;
  • Fragment为什么要开启事务;

2. 解答

同样的,为了解答这个问题,可以做一个小案例。就使用FrameLayout来实现一个小案例。案例效果:
在这里插入图片描述
点击对应的底部Tab可以切换。
activity_main.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="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:id="@+id/fragment_container"
        />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@color/gray"
        />
    <include layout="@layout/layout_bottom"/>
</LinearLayout>

底部Tab文件layout_bottom.xml

<?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="60dp"
    android:orientation="horizontal"
    >

    <TextView
        android:id="@+id/bottom_home"
        android:textColor="@color/gray"
        android:textSize="20sp"
        android:gravity="center"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:text="Home"
        android:onClick="onTabClicked"
        />

    <TextView
        android:id="@+id/bottom_about"
        android:textColor="@color/gray"
        android:textSize="20sp"
        android:gravity="center"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:text="About"
        android:onClick="onTabClicked"
        />

</LinearLayout>

然后建立两个Fragment,这里的页面只需要静态的显示一个文本即可,所以很简单,比如AboutFragment.java

public class AboutFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.layout_about_fragment, container, false);
    }
}

对应的布局文件,layout_about_fragment.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"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/textView_about"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/aboutTex"
        android:textColor="#00BCD4"
        android:textSize="30sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    
</androidx.constraintlayout.widget.ConstraintLayout>

至于另一个HomeFragment也是类似的操作,就不再重复给出。
然后就是MainActivity的代码:

public class MainActivity extends AppCompatActivity {
    private Fragment[] fragments;
    private FragmentManager fragmentManager;
    private TextView[] tabs;
    private int currentTabIndex = 0;
    private HomeFragment homeFragment;
    private AboutFragment aboutFragment;

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


        intiViews();
        fragmentManager.beginTransaction()
                .add(R.id.fragment_container, homeFragment)
                .add(R.id.fragment_container, aboutFragment)
                .hide(aboutFragment)
                .show(homeFragment)
                .commit();
    }

    // onClick监听函数必须声明为public
    public void onTabClicked(View view){
        int index = 0;
        clearTabStyle();
        switch (view.getId()){
            case R.id.bottom_home:
                index = 0;
                break;
            case R.id.bottom_about:
                index = 1;
                break;
        }
        setTabChooseStyle(index);
        if(currentTabIndex != index){
            FragmentTransaction transaction = fragmentManager.beginTransaction();
            transaction.hide(fragments[currentTabIndex]);
            if(!fragments[index].isAdded()){ // 如果没有添加到Fragment列表(FragmentTransaction 中用ArrayList来存储)
                transaction.add(R.id.fragment_container, fragments[index]);
            }
            transaction.show(fragments[index]).commit();
        }
        currentTabIndex = index;
    }

    private void setTabChooseStyle(int index) {
        TextView tab = tabs[index];
        tab.setTextColor(getColor(R.color.white));
        tab.setBackgroundColor(getColor(R.color.purple_700));
    }

    private void clearTabStyle() {
        for (TextView tab : tabs) {
            tab.setTextColor(getColor(R.color.gray));
            tab.setBackgroundColor(getColor(R.color.white));
        }
    }

    private void intiViews() {
        fragmentManager = getSupportFragmentManager();
        homeFragment = new HomeFragment();
        aboutFragment = new AboutFragment();
        fragments = new Fragment[]{ homeFragment, aboutFragment };
        tabs = new TextView[]{findViewById(R.id.bottom_home), findViewById(R.id.bottom_about)};
        setTabChooseStyle(currentTabIndex);
    }
}

在上面的代码中,使用FragmentManager来对Fragment进行管理,在这里指定谁在FrameLayout控件中现实的时候会指定隐藏谁,当前显示谁,也就是这里使用了事务。那么为什么需要使用事务

不妨来看下相关的源码注释:
在这里插入图片描述
使用FragmentManager 可以对 Fragment 进行添加(add),移除(remove),替换(replace),显示(show),隐藏(hide),绑定(attach),解绑(detach)等操作。而要完成这些操作需要通过FragmentTransaction来完成。

事务,就是把一堆事情绑在一起做,都成功了才算完成,否则就恢复之前的样子 。事务通常具有原子性、一致性、隔离性和持久性。

当我们需要使用FragmentManagerFragment进行管理的时候,往往也会做多个操作,而最终设置只显示一个。这个设置过程需要保证原子性、持久性等(比如如果设置了显示多个在没有事务的情况下可能就会崩溃)。所以这里使用事务是合适的。

至于Fragment怎么进行查找?

FragmentManager类中提供了两种方式:
在这里插入图片描述
这里的ID也就是使用的地方的Fragment的布局的id,因为在我的案例中我布局中使用的是FrameLayout,所以需要使用findFragmentByTag方式,可以在添加的时候为每个Fragment关联一个Tag,如下:

fragmentManager.beginTransaction()
        .add(R.id.fragment_container, homeFragment, "FragmentTag_Home")
        .add(R.id.fragment_container, aboutFragment, "FragmentTag_About")
        .hide(aboutFragment)
        .show(homeFragment)
        .commit();

然后可以使用查找,比如使用来Tab点击响应函数中,主要代码如下:

switch (view.getId()){
    case R.id.bottom_home:
        index = 0;
        break;
    case R.id.bottom_about:
        index = 1;
        Fragment aboutView = fragmentManager.findFragmentByTag("FragmentTag_About");
        TextView about = aboutView.getView().findViewById(R.id.textView_about);
        about.setText("点击了!");
        break;
}

因为"FragmentTag_About"所代表的这个FragmentActivity中,所以这里设置正确。

在这里插入图片描述


References

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

梦否

文章对你有用?不妨打赏一毛两毛

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值