Fragment的实现方案

Fragment与Activity有几种方式,今天讲上一讲

##1

xml 布局fragment

很简单,我们先造好fragment 然后再在activity的xml文件中加入

1
2
3
4
5
<TableLayout //这个是fragment
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
</TableLayout>

1
2
3
4
5
6
7
8
<?xml version="1.0" encoding="utf-8"?> //这个是activity的xml,此处直接将fragment拿过来以fragment形式放在activity里
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/hellomoonFragment"
android:name="com.example.asus.hellomoon.HelloMoonFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
></fragment>
1
2
3
4
5
6
7
8
public class HelloMoonActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hello_moon); //直接添加activity ,activity会自己把fragment添加过来;
}
}

2

动态添加:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public void onClick(View v)
{
FragmentManager fm = getFragmentManager();
// 开启Fragment事务
FragmentTransaction transaction = fm.beginTransaction();
switch (v.getId())
{
case R.id.tab_bottom_weixin:
if (mWeixin == null)
{
mWeixin = new ContentFragment();
}
// 使用当前Fragment的布局替代id_content的控件
transaction.replace(R.id.id_content, mWeixin);
break;
case R.id.tab_bottom_friend:
if (mFriend == null)
{
mFriend = new FriendFragment();
}
transaction.replace(R.id.id_content, mFriend);
break;
}
// transaction.addToBackStack();
// 事务提交
transaction.commit();
}
}

利用FragmentManager 动态添加目标xml作为fragment

3超级震撼的小技巧

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public abstract class SingleFragmentActivity extends AppCompatActivity {
protected abstract Fragment createFragment(); //定义createFragemnt的抽象函数
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment);
android.support.v4.app.FragmentManager fm=getSupportFragmentManager();
Fragment fragment =fm.findFragmentById(R.id.fragmentContainer);
if(fragment==null)
{
fragment=createFragment(); //抽象函数获得fragment 在子类中便可具体实现
fm.beginTransaction().add(R.id.fragmentContainer,fragment).commit();
}
}
}
1
2
3
4
5
6
7
public class CrimeActivity extends SingleFragmentActivity {
@Override
return new CrimeFragment(); //整洁多了吧
}