我在使用ViewPager时遇到问题(第一次使用它),viewpager的片段大小未知,我将逐步解释。 这是我的ViewPager:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".events.AllEvents"
android:background="@drawable/gradient"
android:padding="16dp">
<android.support.v4.view.ViewPager
android:id="@+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
</LinearLayout>
我试图使它尽可能简单,这是适配器:
import java.util.List;
class MyPagerAdapter extends FragmentStatePagerAdapter {
private List<Event> events;
public MyPagerAdapter(FragmentManager fm, List<Event> events) {
super(fm);
this.events = events;
}
@Override
public Fragment getItem(int i) {
EventFragment fragment = new EventFragment();
Bundle bundle = new Bundle();
bundle.putSerializable("event", events.get(i));
fragment.setArguments(bundle);
return fragment;
}
@Override
public int getCount() {
return events.size();
}
}
对于片段,我不会放置它的XML文件,因为它有点长,这是它的类:
public class EventFragment extends Fragment {
@BindView(R.id.eventDetailButton)
Button detailsButton;
@BindView(R.id.eventSubscribeButton)
Button subscribeButton;
@BindView(R.id.eventMainImage)
ImageView eventImage;
@BindString(R.string.event_subcribtion)
String eventSubscribtionTag;
Event currentEvent;
public EventFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_event, container, false);
ButterKnife.bind(this, view);
if (getArguments() != null) {
currentEvent = (Event) getArguments().getSerializable("event");
}
System.out.println("*****************************");
Log.d("****FRAGMENT TAG*****", "I REACHED HERE");
System.out.println("*****************************");
return view;
}
当然不会显示日志消息,我没有到达任何地方... 最后是我执行的活动:
public class AllEvents extends AppCompatActivity {
private MyPagerAdapter adapter;
@BindView(R.id.viewPager)
ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_all_events);
ButterKnife.bind(this);
//Apply the adapter
adapter = new MyPagerAdapter(getSupportFragmentManager(), new ArrayList<>(10));
mViewPager.setAdapter(adapter);
}
}
我只想知道,我想念的是什么,或者我在这里做错了什么,我看了很多类似的问题,但是没有一个跟我的一样。
PS:如果我在mViewPager.setAdapter(adapter)
之前或之后放置任何日志消息,它将正常显示在控制台上。