Fragment动态加载

代码
首先在activity中获取FragmentManager message = getFragmentManager();对象,
其次FragmentTransaction tion = message.beginTransaction();
最后引用tion.replace(R.id.infos, new InfoFragment()).commit();


InfoFragment类:

public class InfoFragment extends Fragment {

@Override

public View onCreateView(LayoutInflater inflater, ViewGroup container,

Bundle savedInstanceState) {

View view = inflater.inflate(R.layout.invest, container, false);

return view ;

}


}

activity中代码:


package com.example.dynamicfragmentdemo;


import android.os.Bundle;

import android.support.v4.app.FragmentActivity;

import android.support.v4.app.FragmentManager;

import android.support.v4.app.FragmentTransaction;

import android.util.DisplayMetrics;


public class MainActivity extends FragmentActivity {


@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

//获取FragmentManager对象

FragmentManager fm = getSupportFragmentManager();

//获取FragmentTransaction对象

FragmentTransaction fr = fm.beginTransaction();

//这两步可以换成button其他之类的

DisplayMetrics dm = new DisplayMetrics();

getWindowManager().getDefaultDisplay().getMetrics(dm);

if (dm.widthPixels>dm.heightPixels) {

InfoFragment info = new InfoFragment ();

fr.replace(R.id.rel, info).commit();

}

else{

ShopFragment shop= new ShopFragment();

fr.replace(R.id.rel, shop).commit();

}

}

}

另外的ShopFragment 可以参照InfoFragment

代码完毕

值得注意的是fr.replace();方法中第一个参数一定是与activity关联的布局id,并且使用replace方法必须提交------commit();

ps:replace()方法中第一个参数是代表你在界面上要显示的位置的控件ID。但必须是main布局中的,否则会出异常!

你可能感兴趣的:(Fragment动态加载)