Fragment简介
实例
- 静态使用
效果图
(1)创建fragment
去掉包含工厂方法,去掉包含接口回调
(2)
Fragment1的XML文件效果图
Fragment2的XML文件效果图
主函数的XML: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"
tools:context="lesson10.computer.lesson18.MainActivity">
<fragment
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:id="@+id/frag1"
android:name="lesson10.computer.lesson18.MyFragment1"/>
<fragment
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:id="@+id/frag2"
android:name="lesson10.computer.lesson18.MyFragment2"/>
</LinearLayout>
效果图
- 动态Fragment实例
Fragment1和Fragment2与静态相同
主函数XML只需给布局加一个id即可
主函数XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:id="@+id/main_laylout"
tools:context="lesson10.computer.app2.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="main" />
</RelativeLayout>
后台代码
主函数main
package lesson10.computer.app2;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Display;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取屏幕大小
Display display = this.getWindowManager().getDefaultDisplay();
if(display.getWidth()>display.getHeight()){
//1、创建Fragment实例new
MyFragment1 fragment1 = new MyFragment1();
//2、获取FagmentManager对象,获取碎片管理者对象
FragmentManager manager = this.getSupportFragmentManager();
//3、开启事务
FragmentTransaction trans = manager.beginTransaction();
//4、通过事务,把Fragment添加到容器,replace替换
trans.replace(R.id.main_laylout,fragment1);
//5、提交事务
trans.commit();
}else{
//1、创建Fragment实例new
MyFragment2 fragment2 = new MyFragment2();
//2、获取FagmentManager对象
FragmentManager manager = this.getSupportFragmentManager();
//3、开启事务
FragmentTransaction trans = manager.beginTransaction();
//4、通过事务,把Fragment添加到容器
trans.replace(R.id.main_laylout,fragment2);
//5、提交事务
trans.commit();
}
}
}
效果图