【发布时间】:2016-08-05 09:44:32
【问题描述】:
myFragment 和 myFragment2 都为以下代码返回 null。不确定是什么问题。 This solution 很遗憾没有解决问题,它不是重复的。
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 测试}
【问题讨论】:
-
FragmentTransactions 异步发生,因此当您尝试在该代码中找到您的Fragment时,它们不会完成。如果您确实需要在onCreate()中获得对Fragment的引用,请在commit()呼叫之后立即在支持FragmentManager上呼叫executePendingTransactions()。 -
@MikeM。添加 executePendingTransactions 会使应用崩溃。
-
它仍然是重复的,你现在又遇到了另一个问题。我不知道你在评论亚当的回答中到底是什么意思,但他是正确的(除了布局名称不匹配,现在你已经改变了)。您在
add()调用中传递的ID 必须是Activity布局中ViewGroup的ID,而不是Fragment布局中的ID。 -
@MikeM。你说得对,我忘了片段必须属于一个活动。