fragment我的理解就是有一个小的activity,也可包含布局也有生命周期,可嵌入到activity中
静态添加
在main布局添加fragment标签,这里的android:name="com.example.xyz.fragmentview.FragmentOne"这里的为继承Fragment的类
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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=".MainActivity">
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="切换fragment"
/>
<LinearLayout
android:id="@+id/line1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<fragment
android:id="@+id/fragment1"
android:name="com.example.xyz.fragmentview.FragmentOne"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
</android.support.constraint.ConstraintLayout>
在新建fragment1.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="match_parent"
android:orientation="vertical"
android:gravity="center"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="我是A Fragment"
android:layout_gravity="center"
/>
</LinearLayout>
在新建继承Fragment的类,返回
package com.example.xyz.fragmentview;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentOne extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment1,container,false);
return view;
}
}
这里就已经静态的添加完成了。
动态添加
在之前的基础上新建FragmenTwo类,在建fragment2.xml
public class FragmentTwo extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment2,container,false);
return view;
}
}
在MainActivity.java里修改代码为
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = this.findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FragmentManager fragmentManager = getSupportFragmentManager(); //获取FragmentManager
FragmentTransaction transaction = fragmentManager.beginTransaction(); //开启一个事务
transaction.replace(R.id.fragment1,new FragmentTwo()); //替换为FragmentTwo返回的view
transaction.commit(); //最后提交
}
});
}
}