Android中V4包下的Fragment使用

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




    

myfragment.xml




    


你可能感兴趣的:(android)