【问题标题】:Fragment Transaction.replace() is not working片段 Transaction.replace() 不起作用
【发布时间】:2020-06-28 23:05:57
【问题描述】:

单击按钮时,我试图转到另一个片段,但即使我在另一个片段中,我也需要保留该按钮。我想出了这个,但是当我单击按钮时它没有转到另一个片段。在活动中除了显示第一个片段之外什么都没有发生:

public class Signupnew extends AppCompatActivity {
    Button next;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_signupnew);
        getSupportActionBar().hide();
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        next = (Button) findViewById(R.id.nextf);

        final Fragment fragment = new f1();
        final Fragment fragment2 = new f2();

        FragmentManager fm = getSupportFragmentManager();
        final FragmentTransaction transaction = fm.beginTransaction();
        transaction.replace(R.id.contentFragment, fragment);
        transaction.commit();

        next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (fragment.isAdded()){
                    System.out.println("added");
                    transaction.replace(R.id.contentFragment,fragment2);
                }
                if (fragment2.isAdded()){
                    System.out.println("added2");
                    transaction.replace(R.id.contentFragment, fragment);
                }
            }
        });


    }
}

XML:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:orientation="horizontal"
    android:layout_height="match_parent"
    android:background="@drawable/signupmorenew"
    tools:context=".Signupnew">

    <FrameLayout
        android:id="@+id/contentFragment"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">

        <Button
            android:id="@+id/nextf"
            android:layout_width="350dp"
            android:layout_height="60dp"
            android:layout_marginLeft="28dp"
            android:layout_marginTop="540dp"
            android:background="@drawable/nextsignupandsignin"
            android:fontFamily="@font/varroxfont"
            android:text="التالي"
            android:textColor="#FDBC30"
            android:textSize="20dp" />

    </FrameLayout>




</LinearLayout>

【问题讨论】:

  • 你的片段没有改变?
  • @miladsalimi 是的,它没有。

标签: android android-fragments fragment


【解决方案1】:

您必须调用 FragmentTransaction#commit 来应用更改。另外我认为调用片段事务的整个操作堆栈是一个好习惯。

getSupportFragmentManager().beginTransaction()
   .replace()
   .commit()

【讨论】:

  • 谢谢你,因为stackoverflow规则我会在3分钟后接受你的回答!!
猜你喜欢
  • 1970-01-01
  • 2016-12-20
  • 1970-01-01
  • 2019-02-06
  • 2018-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多