我做了一个抽象布局,我有5-6个framgment,我想在所有片段中有一些相同的组件,就像一个较低的相对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" />
现在我可以从所有片段中显示这个textview,但我只能在主要活动中控制,如何从所有片段中获取它?
答案 0 :(得分:1)
您可以为片段定义Interface
,以便通过您的活动访问View,如果您想要维护它的话:
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从你的Fragament中调用textViewInterface.getTextView()
。
请注意,我已经省略了许多FragmentActivity和Fragment所需的方法。