android fragment test

来源:互联网 发布:穿越火线fps软件 编辑:程序博客网 时间:2024/06/14 08:20
package com.itheima74.fragmenttest;import android.os.Bundle;import android.support.v4.app.Fragment;import android.support.v4.app.FragmentManager;import android.support.v4.app.FragmentTransaction;import android.support.v7.app.AppCompatActivity;import android.view.View;import com.itheima74.fragmenttest.fragment.AnotherRightFragment;import com.itheima74.fragmenttest.fragment.RightFragment;public class MainActivity extends AppCompatActivity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        // 为右半部分动态添加RightFragment        replaceFragment(new RightFragment());        // 为什么这个按钮在LeftFragment mainactivity能找到?因为是静态作为组件添加给了mainactivity        findViewById(R.id.bt_left).setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                // 点击按钮,将RightFragment替换成AnotherRightFragment                replaceFragment(new AnotherRightFragment());            }        });    }    private void replaceFragment(Fragment fragment) {        FragmentManager fragmentManager = getSupportFragmentManager();        FragmentTransaction transaction = fragmentManager.beginTransaction();        transaction.replace(R.id.fl_root, fragment);        // 提交之前将该fragment添加到返回栈,第二个参数一般传null        transaction.addToBackStack(null);        transaction.commit();    }}
<?xml version="1.0" encoding="utf-8"?><LinearLayout 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:orientation="horizontal"    tools:context="com.itheima74.fragmenttest.MainActivity">    <fragment        android:id="@+id/left_fragment"        android:name="com.itheima74.fragmenttest.fragment.LeftFragment"        android:layout_width="0dp"        android:layout_height="match_parent"        android:layout_weight="1" />    <FrameLayout        android:id="@+id/fl_root"        android:layout_width="0dp"        android:layout_height="match_parent"        android:layout_weight="1" /></LinearLayout>




0 0
原创粉丝点击