1、静态加载
直接在xml文件中采用<fragment .../>标签的形式
注意几点:使用静态加载时,起子fragment中的控件也会被加载,列如本例中的button和text
1)fragment.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">
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="按钮" />
</LinearLayout>
2)MyFragment.java
package com.example.fragmentdemo;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.fragment.app.Fragment;
public class MyFragment extends Fragment {
/**
* resource:Fragment需要加载的布局文件
* root:加载layout的父ViewGroup
* attactToRoot:false,不返回父ViewGroup
*/
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment, container, false);
return view;
}
}
3)activity_main.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">
<fragment
android:id="@+id/fragment"
android:name="com.example.fragmentdemo.MyFragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
主意:这里必须指定fragment的id,否则会出现错误:
java.lang.IllegalArgumentException: Binary XML file line #7: Must specify unique android:id, android:tag, or have a parent with an id for com.example.fragmentdemo.MyFragment
4)MainActivity.java
package com.example.fragmentdemo;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private TextView tv;
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//可以直接找到fragment.xml中的button
button = (Button) findViewById(R.id.button);
tv = (TextView) findViewById(R.id.text);
button.setText("在Activity中改变Fragment中的按钮的名字");
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
tv.setText("TextView改变了");
}
});
}
}