问与答 Android用另一个fragmen替换当前片段

vance · 2020-02-20 23:21:06 · 热度: 14

我只是从HoneyComb的片段设计开始。 我创建了两个片段。 当我单击左侧片段中的按钮时,将在右侧创建一个新片段。 同时,当我单击右侧片段中的按钮时(即,下面代码中的DetialsFragment应该替换为另一个片段。main.xml

<?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="horizontal" >
    <fragment class="com.fragment.example.Titles"
        android:id="@+id/titles" android:layout_weight="1"
        android:layout_width="0px"
        android:layout_height="match_parent" />
    <FrameLayout android:id="@+id/details" android:layout_weight="1"
        android:layout_width="0px"
        android:layout_height="match_parent" />

</LinearLayout>

FragmentExample.java

public class FragmentExample extends Activity {
/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}

Titles.java

public class Titles extends Fragment {
    public FragmentTransaction ft;
    @Override
    public View onCreateView(LayoutInflater inflater,
        ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.main1, null);
        Button button1 = (Button)v.findViewById(R.id.button1);
        button1.setText("santhosh");
        button1.setOnClickListener(new OnClickListener() {



            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                 DetailsFragment details = (DetailsFragment)
                            getFragmentManager().findFragmentById(R.id.details);
                    if (details == null || details.getShownIndex() != 1) {
                        // Make new fragment to show this selection.
                        details = DetailsFragment.newInstance(1);

                        // Execute a transaction, replacing any existing
                        // fragment with this one inside the frame.
                        ft
                                = getFragmentManager().beginTransaction();
                        ft.add(R.id.details, details, "detail");
                        ft.setTransition(
                                FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                        ft.commit();
                    }
            }

        });
        return v;
    }
}

DetailsFragment.java

public class DetailsFragment extends Fragment {
    /**
     * Create a new instance of DetailsFragment, initialized to
     * show the text at 'index'.
     */
    Titles title = new Titles();
    String[] titles = {"Title1", "Title2", "Title3", "Title4"};
    public static DetailsFragment newInstance(int index) {
        DetailsFragment f = new DetailsFragment();

        // Supply index input as an argument.
        Bundle args = new Bundle();
        args.putInt("index", index);
        f.setArguments(args);

        return f;
    }

    public int getShownIndex() {
        return getArguments().getInt("index", 0);
    }

    @Override
    public View onCreateView(LayoutInflater inflater,
        ViewGroup container, Bundle savedInstanceState) {
        if (container == null) {
            // Currently in a layout without a container, so no
            // reason to create our view.
            return null;
        }
        Button button = new Button(getActivity());
        button.setText("Next");
        button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
            }
        });
        return button;
    }
}

猜你喜欢:
共收到 5 条回复
sammy #1 · 2020-02-20 23:21:06

然后,只要显示了您的按钮并且触发了click事件,您就可以在click事件中调用以下命令:

final FragmentTransaction ft = getFragmentManager().beginTransaction(); 
ft.replace(R.id.details, new NewFragmentToReplace(), "NewFragmentTag"); 
ft.commit(); 

并且如果您想返回到单击返回的DetailsFragment,请确保将以上交易记录添加到后台堆栈中,即

ft.addToBackStack(null);

还是我错过了什么? 或者,有些人建议您的活动获得按钮的click事件,并负责替换详细信息窗格中的片段。

sjef #2 · 2020-02-20 23:21:07

您可以尝试以下代码。 这是从旧片段中推送新片段的非常简单的方法。

private int mContainerId;
private FragmentTransaction fragmentTransaction;
private FragmentManager fragmentManager;
private final static String TAG = "DashBoardActivity";

public void replaceFragment(Fragment fragment, String TAG) {

    try {
        fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(mContainerId, fragment, tag);
        fragmentTransaction.addToBackStack(tag);
        fragmentTransaction.commitAllowingStateLoss();

    } catch (Exception e) {
        // TODO: handle exception
    }

}
kristopher #3 · 2020-02-20 23:21:08

在您的代码中将android.support.v4.app用于FragmentManager和FragmentTransaction,它对我有用。

DetailsFragment detailsFragment = new DetailsFragment();
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.details,detailsFragment);
fragmentTransaction.commit();
cedric #4 · 2020-02-20 23:21:09

如果您拥有现有片段的句柄,则可以将其替换为片段的ID。

Kotlin中的示例:

fun aTestFuction() {
   val existingFragment = MyExistingFragment() //Get it from somewhere, this is a dirty example
   val newFragment = MyNewFragment()
   replaceFragment(existingFragment, newFragment, "myTag")
}

fun replaceFragment(existing: Fragment, new: Fragment, tag: String? = null) {
    supportFragmentManager.beginTransaction().replace(existing.id, new, tag).commit()
}
trayvon #5 · 2020-02-20 23:21:10

用Fragment替换非常简单。

DataFromDb changeActivity = new DataFromDb();
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.changeFrg, changeActivity);
    transaction.commit();
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册