【面试】如何向Activity当中动态添加Fragment

①建立一个继承于Fragment的类Fragment1.class;

import android.annotation.SuppressLint;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

@SuppressLint("NewApi")
public class Frament1 extends Fragment {

  @SuppressLint("NewApi")
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    return inflater.inflate(R.layout.frament1, container,false);
  }
}

②为Fragment1建立属于自己的layout为fragment1.xml;

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"   
    android:background="#00FF00">
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="This is fragment #1"
        android:textSize="25sp"
    />
</LinearLayout>

③在Activity对应的layout布局当中添加<fragment/>

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <fragment 
        android:name="com.example.frament.Frament1"  类名的完整地址
        android:id="@+id/frament1"
        android:layout_weight="1"
        android:layout_height="fill_parent" 
        android:layout_width="fill_parent"
    />
</LinearLayout>

  

④在Activity当中引用FragmentManager管理需要添加的Fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.Display;

public class MainActivity1 extends Activity {

  @SuppressLint("NewApi")
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //setContentView(R.layout.main);
    
    //向活动添加碎片,根据屏幕的纵向和横向显示
    //1,获取碎片管理器
    FragmentManager fragment=getFragmentManager();
    //2,碎片的显示需要使用FragmentTransaction类操作
    FragmentTransaction transacction=fragment.beginTransaction();
    //获取java类
    Frament1 frament1 =  new Frament1();
    transacction.replace(android.R.id.content, frament1);
    //使用FragmentTransaction必须要commit   
transacction.commit();
}

更多线索请参考原文

posted @ 2015-11-28 15:17  gzejia  阅读(1367)  评论(0编辑  收藏  举报