我试图通过获取容器中的当前片段并调用其方法来更新我的UI。我的布局如下:
<?xml version="1.0" encoding="UTF-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- The main content view -->
<FrameLayout
android:id="@+id/frmContentFrame"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true" />
<!-- The navigation drawer -->
<ListView android:id="@+id/lstLeftDrawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:background="@color/SlideMenuBlue"
android:divider="@color/White"
android:dividerHeight="1dp"
android:paddingTop="@dimen/list_padding"
android:paddingBottom="@dimen/list_padding"/>
</android.support.v4.widget.DrawerLayout>
我正在片段之间转换(android.support.v4.app),如此
//Switches views
public void switchContent(final Fragment fragment) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.frmContentFrame, fragment, "CURRENT_FRAGMENT")
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.addToBackStack(null)
.commitAllowingStateLoss();
}
当我调用我的更新UI方法时,我的片段为空。这是代码
public void updateUI() {
Fragment fragment = getSupportFragmentManager().findFragmentByTag("CURRENT_FRAGMENT");
System.out.println(fragment);
if((FragmentA) getSupportFragmentManager().findFragmentByTag("CURRENT_FRAGMENT") != null){
FragmentA frag = (FragmentA) getSupportFragmentManager().findFragmentByTag("CURRENT_FRAGMENT");
frag.updateUIStatusA();
}
else if((FragmentB) getSupportFragmentManager().findFragmentByTag("CURRENT_FRAGMENT") != null){
FragmentB frag = (FragmentB) getSupportFragmentManager().findFragmentByTag("CURRENT_FRAGMENT");
frag.updateUIStatusB();
}
}
奇怪的是,当片段返回null时,我得到一个ClassCastException
,如下所示
java.lang.ClassCastException: com.example.activity.fragments.FragmentB cannot be cast to com.example.activity.fragments.FragmentA
为什么它在错误中知道我的容器中有哪些片段,但在我尝试检索它时返回null?
任何帮助都会很棒
由于
答案 0 :(得分:1)
尝试使用唯一标记,不要忘记在backstack
中添加标记。例如:
//Switches views
public void switchContent(final Fragment fragment) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.frmContentFrame, fragment, fragment.getClass().getSimpleName())
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.addToBackStack(fragment.getClass().getSimpleName())
.commitAllowingStateLoss();
}
然后您的更新方法可能如下所示
public void updateUI() {
Fragment fragmentA = getSupportFragmentManager().findFragmentByTag(FragmentA.class.getSimpleName());
Fragment fragmentB = getSupportFragmentManager().findFragmentByTag(FragmentB.class.getSimpleName());
if (fragmentA != null)
fragmentA.updateUIstatusA();
if (fragmentB != null)
fragmentB.updateUIstatusB();
}