美文网首页
FrameLayout添加fragment

FrameLayout添加fragment

作者: 凌康ACG | 来源:发表于2019-10-01 15:05 被阅读0次

1、在activity_main中加入FrameLayout

    <FrameLayout
        android:id="@+id/fl_home"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">
    </FrameLayout>

2、创建home_user_fragment.xml和UserFragment.java

<?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"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="188dp"
        android:layout_marginTop="216dp"
        android:text="用户"
        android:textSize="20dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</LinearLayout>
package com.lingkang.top.seesister.activity.home.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.lingkang.top.seesister.R;

public class UserFragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return LayoutInflater.from(getActivity()).inflate(R.layout.home_user_fragment, container, false);
    }
}

3、在MainActiviy中

// 定义
    private FragmentManager supportFragmentManager;
    private FragmentTransaction fragmentTransaction;
// ..........
        //获取管理者
        supportFragmentManager = getSupportFragmentManager();
        //开启事务
        fragmentTransaction =  supportFragmentManager.beginTransaction();
//添加fragment上去
fragmentTransaction.add(R.id.fl_home, new UserFragment()).commit();

相关文章

网友评论

      本文标题:FrameLayout添加fragment

      本文链接:https://www.haomeiwen.com/subject/wdzeyctx.html