Android笔记之Fragment初步

1、 要使用fragment,首先需要创建一个类继承

android.app.Fragment;

Fragment1.java(需要给Fragment1配置布局文件f1.xml)

Android笔记之Fragment初步
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Fragment1 extends Fragment {

    //初始化Fragment,实例化在Fragment中的成员变量
    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
    }
    
    //给Fragment 加载UI布局,组件例如button,textview等等在这里去初始化
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub //这个布局没有父布局,所以root置空 View view=inflater.inflate(R.layout.f1, null); return view; } }
Android笔记之Fragment初步

 

2、Activity调用

Android笔记之Fragment初步
import android.os.Bundle;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.view.Menu;

public class MainActivity extends Activity {

    private FragmentManager manager;
    private FragmentTransaction transaction;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        //将activity_main中的某一块换成fragment1
        manager=getFragmentManager();
        transaction=manager.beginTransaction();
        Fragment1 fragment1=new Fragment1();
        //content_frame的内容换成fragment1
        transaction.add(R.id.content_frame, fragment1);
        transaction.commit();
    }

}
Android笔记之Fragment初步

 

Done!

Android笔记之Fragment初步,布布扣,bubuko.com

Android笔记之Fragment初步

上一篇:xcode5.1下发布app出错解决


下一篇:用谷歌浏览器来当手机模拟器