在用fragment框架做app时候,用replace()函数,想点击按钮切换到一个新的fragment,可是运行时候新的fragment显示在按钮的下方。。。求教!
在网上看有人说改一下activity_main的fragment改成FragmentLayout 试了也没用。。
使用FrameLayout+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" >
并模猛 <LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="a"
android:text="Button" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="b"
android:text="Button" />
</LinearLayout>
<FrameLayout
android:id="@+id/myframe"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
</FrameLayout>
</LinearLayout>
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
public class MainActivity extends FragmentActivity {
private FragmentTransaction fragmentTransaction;
private FragmentManager fragmentManager;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragmentManager = getSupportFragmentManager();
}
public void a(View view) {
AFragment fragment = new 码空AFragment();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.myframe, fragment);
fragmentTransaction.commit();
绝桥 }
public void b(View view) {
BFragment fragment = new BFragment();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.myframe, fragment);
fragmentTransaction.commit();
}
}
通FragmentTransactionattachdetach实现
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
if (mLastFragment != null) {
//detachfragment
fragmentTransaction.detach(mLastFragment);
}
//找fragmentfindFragmentByTag自定此行义
Fragment fragment = fragmentManager.findFragmentByTag(tabName);
if (fragment == null) {
//add
fragmentTransaction.add(R.id.layout_fragment_id, fragment, tabName);
} else {
//attach
fragmentTransaction.attach(fragment);
}
//弯饥保森闹哗存fragment
mLastFragment = fragment;
//事务commit
fragmentTransaction.commitAllowingStateLoss();
fragmentManager.executePendingTransactions();