1. 前言
今天在面试顺丰的时候遇到了这两个问题。平时确实没有注意过这两个问题,这里记录下。另外面试过程了解到顺丰偏向于跨平台开发,不太偏向
Android
原生开发。所以在面试过程中还问了前端的知识,比如为什么使用虚拟
Dom
、
Vue
的渲染过程等。
-
怎么进行查找;Fragment
-
为什么要开启事务;Fragment
2. 解答
同样的,为了解答这个问题,可以做一个小案例。就使用
FrameLayout
来实现一个小案例。案例效果:
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiI2EzX4xSZz91ZsAzNfRHLGZkRGZkRfJ3bs92YscTMfVmepNHLtNkW102SxVTQClGVF5UMR9Fd4VGdsATNfd3bkFGazxycykFaKdkYzZUbapXNXlleSdVY2pESa9VZwlHdssmch1mclRXY39CXldWYtlWPzNXZj9mcw1ycz9WL49zZuBnLlFWNxETMlZTOxUjZmJWNhhjNyQTOmFjN0kTOjVWMyQ2Lc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
点击对应的底部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
来完成。
事务,就是把一堆事情绑在一起做,都成功了才算完成,否则就恢复之前的样子 。事务通常具有原子性、一致性、隔离性和持久性。
当我们需要使用
FragmentManager
对
Fragment
进行管理的时候,往往也会做多个操作,而最终设置只显示一个。这个设置过程需要保证原子性、持久性等(比如如果设置了显示多个在没有事务的情况下可能就会崩溃)。所以这里使用事务是合适的。
至于
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
"所代表的这个
Fragment
在
Activity
中,所以这里设置正确。
References
- Fragment学习之findFragmentById的使用
- fragment通过findFragmentByTag获取