zoukankan      html  css  js  c++  java
  • 动态创建fragment

    MainActivity

    public class MainActivity extends Activity {

     @Override

     protected void onCreate(Bundle savedInstanceState) {

      super.onCreate(savedInstanceState);

      setContentView(R.layout.activity_main);

      int width = getWindowManager().getDefaultDisplay().getWidth();

      int length = getWindowManager().getDefaultDisplay().getHeight();

      FragmentManager fm = getFragmentManager();

      FragmentTransaction ft = fm.beginTransaction();

      if (width > length) {

       ft.replace(android.R.id.content, new Fragment1());

      } else {

       ft.replace(android.R.id.content, new Fragment2());

      }

      ft.commit();

     }

    }

    定义两个Fragment

    public class Fragment1 extends Fragment{

     @Override

     public View onCreateView(LayoutInflater inflater, ViewGroup container,

       Bundle savedInstanceState) {

      return inflater.inflate(R.layout.fragment1, null);

     }

    }

    public class Fragment2 extends Fragment{

     @Override

     public View onCreateView(LayoutInflater inflater, ViewGroup container,

       Bundle savedInstanceState) {

      return inflater.inflate(R.layout.fragment2, null);

     }

    }

    布局文件

    activity_main

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

        xmlns:tools="http://schemas.android.com/tools"

        android:layout_width="match_parent"

        android:layout_height="match_parent"

        android:paddingBottom="@dimen/activity_vertical_margin"

        android:paddingLeft="@dimen/activity_horizontal_margin"

        android:paddingRight="@dimen/activity_horizontal_margin"

        android:paddingTop="@dimen/activity_vertical_margin"

        tools:context=".MainActivity" >

       

    </RelativeLayout>

    fragment1

    <?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:background="#aa0000ff"

        android:orientation="vertical" >

    </LinearLayout>

    fragment2

    <?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:background="#00ff00"

        android:orientation="vertical" >

    </LinearLayout>

  • 相关阅读:
    《超越自己》--刘墉
    《菊与刀》--[美]鲁思·本尼迪克特(Ruth Benedict)
    《暧昧的日本人》--李兆忠
    《女性的选择》--[日]今野由梨
    《懂得低头,才能出头》--李艳
    原来还有这样的记词方法_Java版记不规则动词_博主推荐
    《永不止步》--[奥]力克胡哲
    C#面向服务WebService从入门到精通
    C# Windows服务开发从入门到精通
    sql server递归查询
  • 原文地址:https://www.cnblogs.com/freenovo/p/4469789.html
Copyright © 2011-2022 走看看