myFragment和myFragment2都为以下代码返回null。不确定是什么问题。 This solution遗憾的是,{{3}}没有解决问题,但这并不重复。
MainActivity
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:找不到id 0x7f0b0056的视图(name.com.viewpagercode:id / nonce_input_fragment)片段NonceInputFragment {cece542#0 id = 0x7f0b0056 test}
答案 0 :(得分:0)
您的布局R.layout.identify_fragment
没有android:id="@+id/nonce_input_fragment"
的视图。
具体来说,这一行:
transaction.add(R.id.nonce_input_fragment,nonceInputFragment,"test");
说&#34;将此片段添加到此活动中,并将其放入ID为nonce_input_fragment
的容器中。该异常表示您的活动中不存在此类视图 - 这意味着您的布局(identify_fragment
)需要添加如下内容:
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/nonce_fragment" />