自动生成java文件,创建Fragment
package com.example.myfragment;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class BlankFragment extends Fragment {
public BlankFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View inflate = inflater.inflate(R.layout.fragment_blank, container, false);
return inflate;
}
}
静态加载
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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">
<!--静态添加 name属性是fragment的全限定名-->
<fragment
android:id="@+id/fg"
android:name="com.example.myday0224remoteview.FristBlankFragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</fragment>
</LinearLayout>
动态加载
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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">
<!--动态添加-->
<FrameLayout
android:id="@+id/frame_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</FrameLayout>
</LinearLayout>
动态加载 java代码
package com.example.myfragment;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager supportFragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = supportFragmentManager.beginTransaction();
BlankFragment blankFragment = new BlankFragment();
BlankFragment2 blankFragment2 = new BlankFragment2();
fragmentTransaction.add(R.id.frame_id, blankFragment);
fragmentTransaction.remove(blankFragment);
fragmentTransaction.replace(R.id.frame_id, blankFragment2);
fragmentTransaction.hide(blankFragment2);
fragmentTransaction.commit();
}
}