我有一个Fragment
是ViewPager
的一部分。在这个Fragment
中,我有一个ViewGroup
孩子。现在,为什么在实例化MainActivity
和onCreate()
后在ViewPager
的adapter
中,我的Container
正在获取null
?
这是我的onCreate()
:
private MyAdapter mAdapter;
private ViewPager mPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAdapter = new MyAdapter(getSupportFragmentManager());
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mContainerView = (ViewGroup) findViewById(R.id.container);
//Here mContainerView is already null
...
}
这是包含
Fragment
的ViewPager
的一部分中的mContainerView
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ScrollView android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- This is my ViewGroup -->
<LinearLayout android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:showDividers="middle"
android:divider="?android:dividerHorizontal"
android:animateLayoutChanges="true"
android:paddingLeft="16dp"
android:paddingRight="16dp" />
</ScrollView>
<TextView android:id="@android:id/empty"
style="?android:textAppearanceSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:padding="32dp"
android:text="@string/message_empty_layout_changes"
android:textColor="?android:textColorSecondary" />
</FrameLayout>
最佳答案
如果我正确地阅读了您的问题,则您正在尝试使用Fragment
的View
方法访问Activity
的findViewById()
(及其子级)。这不应该起作用,因为Fragment
会夸大其自身的布局,并且Fragments
不是传统的Views
。
如果您知道Fragment
已实例化并且可以检索它,则可以使用以下方法获取ViewGroup
的实例
yourFragment#getView().findViewById()
如果不是,则可以使用接受
Activity
作为参数的方法来创建ViewGroup
实现的接口。然后在Fragment的onCreateView()
中,让Fragment将ViewGroup
传递给接口。您可以直接转换为Activity
,但界面更干净。例如
public class Fragment {
public interface ViewGroupCreateListener{
public void onViewGroupCreated (ViewGroup v);
}
private ViewGroupCreateListener listener;
public void onAttach (Activity a){
super.onAttach (a);
listener = (ViewGroupCreateListener) a;
}
public View onCreateView (/*all its arguments here*/){
View v = inflater.inflate (R.layout.your_layout);
ViewGroup group = v.findViewById (R.id.container);
listener.onViewGroupCreated(group);
return v;
}
}
您的
Activity
看起来像:public class MainActivity extends Activity implements ViewGroupCreateListener, OtherInterface1, OtherInterface2{
private ViewGroup mViewGroup;
public void onViewGroupCreated (ViewGroup v){
mViewGroup = v;
}
}
这很好,因为如果寻呼机重新实例化
Fragment
,则Activity仍将获得ViewGroup
的有效实例。或者,如果根据您实际使用此
ViewGroup
所要实现的目标,则可以在Fragment
本身内部进行此处理。