首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在所有片段中创建公共视图

在所有片段中创建公共视图
EN

Stack Overflow用户
提问于 2014-05-28 19:55:48
回答 1查看 474关注 0票数 0

我做了一个抽屉布局,我有5-6框架,我希望在所有片段中都有一个相同的组件,比如一个较低的相对ayout和一个webview,它将显示在我在下面代码中写的所有片段中。

代码语言:javascript
运行
复制
<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" >

<!-- Framelayout to display Fragments -->

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

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent" >

        <TextView
            android:id="@+id/imageView1"
            android:layout_width="120dp"
            android:layout_height="60dp"
            android:layout_alignParentBottom="true"
            android:layout_alignParentLeft="false"
            android:layout_alignParentRight="false"
            android:layout_alignParentTop="true"
            android:layout_margin="30dp" />
    </RelativeLayout>
</FrameLayout>

<!-- Listview to display slider menu -->

<ListView
    android:id="@+id/list_slidermenu"
    android:layout_width="240dp"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:background="@color/list_background"
    android:choiceMode="singleChoice"
    android:divider="@color/list_divider"
    android:dividerHeight="1dp"
    android:listSelector="@drawable/list_selector" />

现在我可以从所有片段中显示这个文本视图,但我只能在主活动中进行控制,如何从所有片段中访问它?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-05-28 20:15:45

如果要维护视图,可以为片段定义一个Interface,以便通过您的活动访问视图:

代码语言:javascript
运行
复制
public class MyBaseFragment extends Fragment
{
    MyTextViewInterface textViewInterface;

    public Interface TextViewInterface
    {
        public TextView getTextView();
    }

    @Override
    public void onAttach(Activity activity)
    {
        super.onAttach(activity);
        try
        {
            textViewInterface = (MyTextViewInterface) activity;
        }
        catch (ClassCastException e)
        {
            Log.e(TAG, "Parent Activity deosn't implement 'MyTextViewInterface'");
            throw new ClassCastException(activity.toString()
                    + " must implement MyTextViewInterface");
        }
    }
}

public class MyActivity extends FragmentActivity implements MyTextViewInterface
{
    TextView textView;
    ...

    @Override
    public TextView getTextView()
    {
        return this.textView;
    }
}

要获得TextView,只需从框架中调用textViewInterface.getTextView()即可。

请注意,我省略了许多FragmentActivity和片段所需的方法。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23920713

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档