findFragmentById为使用FragmentTransaction添加的Fragment返回null


对于下面的代码,myFragment和myFragment2都返回null。不确定问题是什么。不幸的是,这个解决方案没有解决问题,它不是重复的。

主要活动

public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    NonceInputFragment nonceInputFragment = new NonceInputFragment();
    transaction.add(R.id.nonce_input_fragment,nonceInputFragment,"test");
    transaction.commit();
    // It crashes on this line:
    getSupportFragmentManager().executePendingTransactions();
    NonceInputFragment myFragment = (NonceInputFragment) getSupportFragmentManager().findFragmentById(R.id.nonce_input_fragment);
    NonceInputFragment myFragment2 = (NonceInputFragment) getSupportFragmentManager().findFragmentByTag("test");
    }
}

nonce_input.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/nonce_input_fragment">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Medium Text"
        android:id="@+id/tvLabel"
        android:layout_gravity="center_horizontal" />
</LinearLayout>

NonceInputFragment

public class NonceInputFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.nonce_input, container, false);
        return view;
    }
}

错误消息:
java.lang.RuntimeException:无法启动活动ComponentInfo{name.com.viewpagercode/name.com.viewpagercode.MainActivity}:java.lang.IllegalArgumentException:找不到片段NonceInputFragment{cece542#0 id=0x7f0b0056 test}的id 0x7f00b0056(name.com.vviewpagercode:id/nonce_input_fragment(的视图

您的布局R.layout.identify_fragment没有包含android:id="@+id/nonce_input_fragment"的视图。

具体来说,这一行:

transaction.add(R.id.nonce_input_fragment,nonceInputFragment,"test");

正在说"将此片段添加到此活动,并将其放入id为nonce_input_fragment的容器中。异常表示您的活动中不存在此类视图,这意味着您的布局(identify_fragment(需要添加类似的内容:

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/nonce_fragment" />

最新更新