package com.zdsoft.fragment1205;
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.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private Fragment fragment;
private Button bt_change;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取fragment管理器
FragmentManager fragmentManager = getSupportFragmentManager();
//获取事务
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
//添加fragment
fragment = new OneFragment();
fragmentTransaction.add(R.id.fl, fragment);
//提交事务
fragmentTransaction.commit();
bt_change = (Button) findViewById(R.id.bt_change);
bt_change.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//获取fragment管理器
FragmentManager fragmentManager = getSupportFragmentManager();
//获取事务
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
//切换fragment
if (fragment instanceof OneFragment) {
fragment = new TwoFragment();
} else {
fragment = new OneFragment();
}
fragmentTransaction.replace(R.id.fl, fragment);
//提交事务
fragmentTransaction.commit();
}
});
}
}
package com.zdsoft.fragment1205;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {@link Fragment} subclass.
*/
public class OneFragment extends Fragment {
public OneFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_one, container, false);
}
}
package com.zdsoft.fragment1205;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {@link Fragment} subclass.
*/
public class TwoFragment extends Fragment {
public TwoFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_two, container, false);
}
}
<?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">
<Button
android:id="@+id/bt_change"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="跳转" />
<FrameLayout
android:id="@+id/fl"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>