【Android】20、在运行时添加碎片

来源:互联网 发布:vb 按键精灵 编辑:程序博客网 时间:2024/05/01 17:24

1、接文章19中的案例,修改mainactivity.xml布局文件,删除或注释掉fragment标签

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="horizontal">    <!--<fragment-->        <!--android:name="com.wxy.fragment.Fragment1"-->        <!--android:id="@+id/fragment1"-->        <!--android:layout_width="0px"-->        <!--android:layout_weight="1"-->        <!--android:layout_height="match_parent"/>-->    <!--<fragment-->        <!--android:name="com.wxy.fragment.Fragment2"-->        <!--android:id="@+id/fragment2"-->        <!--android:layout_width="0px"-->        <!--android:layout_weight="1"-->        <!--android:layout_height="match_parent"/>--></LinearLayout>

2、修改mainactivity.java文件

public class MainActivity extends AppCompatActivity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);//        setContentView(R.layout.main);        android.app.FragmentManager fragmentManager = getFragmentManager();        android.app.FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();        //get the current display info        WindowManager wm=getWindowManager();        Display d=wm.getDefaultDisplay();        if (d.getWidth()>d.getHeight()){            //landscape mode            Fragment1 fragment1 =new Fragment1();            //android.R.id.content refers to the content            //view of the activity            fragmentTransaction.replace(android.R.id.content, fragment1);        }        else {            //portrait mode            Fragment2 fragment2 =new Fragment2();            fragmentTransaction.replace(android.R.id.content, fragment2);        }        fragmentTransaction.commit();    }}



0 0
原创粉丝点击