MainActivity
package com.xw.fragmentv4;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import com.xw.fragmentv4.fragment.MyFragment;
/**
* 演示v4包下fragment的使用
* 注意:
* 1.使用v4包下的fragment时需要引入activity继承FragmentActivity
* 2.获取FragmentManager对象时需要调用getSupportFragmentManager()方法获取对象
* 3.使用v4包下的fragment时 相关的对象也需要导入对应的v4包下
*/
public class MainActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.layout,new MyFragment());
transaction.commit();
}
}
Myfragment
package com.xw.fragmentv4.fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.xw.fragmentv4.R;
/**
* Created by Administrator on 2018/4/27.
*/
public class MyFragment extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup con1t1ainer, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.myfragment,null);
return view;
}
}
布局文件:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.xw.fragmentv4.MainActivity">
<LinearLayout
android:id="@+id/layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
></LinearLayout>
</RelativeLayout>
myfragment.xml
<?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">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="fragment内容"
android:textColor="#aa0000"
android:layout_centerInParent="true"
/>
</RelativeLayout>