Android:如何从 ViewPager 中的片段检索 Activity 父级
Android: How to retrieve Activity parent from a fragment inside a ViewPager
从我的片段中,在 ViewPager 中,我想获得父 Activity:
我片段中的方法:
@Override
public void setMenuVisibility(final boolean visible) {
super.setMenuVisibility(visible);
if (visible) {
Activity aa = getActivity(); >>> It's always NULL !!
aa.findViewById(R.id.my_special_button).setVisibility(View.VISIBLE);
}
}
这个Activity的布局:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
....
<android.support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
....
<Button
android:id="@+id/my_special_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="@color/background"/>
您可能需要覆盖片段中的 OnAttach 方法并将 Activity 实例保存到片段中的局部变量。
从我的片段中,在 ViewPager 中,我想获得父 Activity:
我片段中的方法:
@Override
public void setMenuVisibility(final boolean visible) {
super.setMenuVisibility(visible);
if (visible) {
Activity aa = getActivity(); >>> It's always NULL !!
aa.findViewById(R.id.my_special_button).setVisibility(View.VISIBLE);
}
}
这个Activity的布局:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
....
<android.support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
....
<Button
android:id="@+id/my_special_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="@color/background"/>
您可能需要覆盖片段中的 OnAttach 方法并将 Activity 实例保存到片段中的局部变量。