我做了一个抽屉布局,我有5-6框架,我希望在所有片段中都有一个相同的组件,比如一个较低的相对ayout和一个webview,它将显示在我在下面代码中写的所有片段中。
<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" />
现在我可以从所有片段中显示这个文本视图,但我只能在主活动中进行控制,如何从所有片段中访问它?
发布于 2014-05-28 20:15:45
如果要维护视图,可以为片段定义一个Interface
,以便通过您的活动访问视图:
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和片段所需的方法。
https://stackoverflow.com/questions/23920713
复制相似问题