【问题标题】:Change fragments in Switch Statement在 Switch 语句中更改片段
【发布时间】:2015-12-29 19:30:05
【问题描述】:

我有一个FragmentAcivity 用于创建动态 UI。我希望能够根据 FragmentActivity 收到的意图,将仅包含文本的片段替换为可能必须在线发布内容的片段,例如 Twitter 或服务器。

我使用了一个开关(如下所示),Android Studio 告诉我它无法解析我的事务对象上的第二个 add()(我在其中添加 postFrag)方法。我错过了什么?如果使用开关是个坏主意,那还能怎么做呢?

'fragView` 是片段容器。

private void showContentInContainer() {

    // Get intent to determine next action
    int workType = getIntent().getExtras().getInt(MainActivity.TAG_FRAGWORK);

    FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction transaction = fragmentManager.beginTransaction();

    // Add the appropriate frag
    switch (workType) {
        case MainActivity.VIEW_RIGHTS :
            // TODO: Pass a rights fragment
            RightsFragment rightsFrag = new RightsFragment();
            transaction.add(R.id.fragView, rightsFrag);
            break;
        case MainActivity.VIEW_SRA :
            // TODO: Pass a view SRA fragment
            PostFragment postFrag = new PostFragment();
            transaction.add(R.id.fragView, postFrag);
            break;
        default: break;
    }
    transaction.commit(); // publish changes
}

编辑:添加片段容器视图的 XML

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ScrollView
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1">
    <fragment
        android:id="@+id/fragView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
</ScrollView>

<fragment
    android:id="@+id/adFragment_2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:name="com.frankbrenyahapps.citisafe.adFragment"
    tools:layout="@layout/fragment_ad"  />
</LinearLayout>

【问题讨论】:

    标签: java android android-fragments android-studio


    【解决方案1】:

    我的猜测是 postFrag 实际上不是 Fragment 的子类,或者您将 android.support.v4.app.Fragment 与 android.app.Fragment 混为一谈。 它与switch语句无关。

    【讨论】:

    • 嘿@Rediska 在我的片段容器上它希望我在编辑期间有一个布局,即使我在添加 FragmentActivity 时动态添加一个布局。如果我不添加一个活动崩溃,如果我这样做,我会得到重复的片段。是因为我需要一个框架布局吗?知道如何解决这个问题吗?
    • 不看代码就很难说出任何事情,但是不,您不必使用 FrameLayout。事实上,您可以在同一个容器中拥有许多片段。为了避免重复片段的混乱,我总是使用 transaction.replace(id,fragment)。
    • @Resiska 相同的代码。我的片段只是在 onCreate 中膨胀它们的布局(基本上是空的),而 FragmentActivity 在 fragView 中膨胀它们(一个等待填充的空片段元素)。我更新以显示我的 XML。
    • 将 android:id="@+id/fragView" 移动到 ScrollView 并移除片段标签。添加片段时,您指定 ViewGroup 容器的 id,而不是片段标签的 id。
    • 啊,这就是他们的意思。谢谢@Rediska
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    相关资源
    最近更新 更多