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); } }
|
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(); FragmentTransaction transaction = fm.beginTransaction(); switch (v.getId()) { case R.id.tab_bottom_weixin: if (mWeixin == null) { mWeixin = new ContentFragment(); } 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.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(); @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(); fm.beginTransaction().add(R.id.fragmentContainer,fragment).commit(); } } }
|
1 2 3 4 5 6 7
| public class CrimeActivity extends SingleFragmentActivity { @Override return new CrimeFragment(); }
|