Android中V4包下的Fragment使用

本文详细介绍了在Android中如何使用V4包下的Fragment,包括在MainActivity中添加和管理Fragment,以及对应的布局文件activity_main.xml和myfragment.xml的配置与应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

MainActivity

package com.xw.fragmentv4;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

import com.xw.fragmentv4.fragment.MyFragment;

/**
 * 演示v4包下fragment的使用
 *  注意:
 *  1.使用v4包下的fragment时需要引入activity继承FragmentActivity
 *  2.获取FragmentManager对象时需要调用getSupportFragmentManager()方法获取对象
 *  3.使用v4包下的fragment时 相关的对象也需要导入对应的v4包下
 */
public class MainActivity extends FragmentActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.add(R.id.layout,new MyFragment());
        transaction.commit();
    }
}

Myfragment

package com.xw.fragmentv4.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.xw.fragmentv4.R;

/**
 * Created by Administrator on 2018/4/27.
 */

public class MyFragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup con1t1ainer, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.myfragment,null);
        return view;
    }
}

布局文件:

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="com.xw.fragmentv4.MainActivity">

    <LinearLayout
        android:id="@+id/layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        ></LinearLayout>
</RelativeLayout>

myfragment.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="fragment内容"
        android:textColor="#aa0000"
        android:layout_centerInParent="true"
        />
</RelativeLayout>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值