我还在学习并试图实现PageAdapter,我不了解一些事情。
public class Card
{
public Card(final Context iContext, final Class<?> iNextActivity, int iDrawable)
{
drawable = iDrawable;
onClick = new View.OnClickListener()
{
@Override
public void onClick(View view)
{
//this just opens an activity using Intent
ActivityManipulator.openActivity(iContext, iNextActivity);
}
};
}
public View.OnClickListener onClick;
public int drawable;
}
public class InfiniteCycleViewPagerAdapter extends PagerAdapter {
public InfiniteCycleViewPagerAdapter(Context iContext, List<Card> iCards)
{
cards = iCards;
context = iContext;
layoutInflater = LayoutInflater.from(iContext);
}
@Override
public int getCount() {
return cards.size();
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
@Override
public void destroyItem(ViewGroup container, int position, Object object)
{
container.removeView((View) object);
}
@Override
public Object instantiateItem(ViewGroup container, final int position)
{
Log.d("instantiateItem", Integer.toString(position));
View view = layoutInflater.inflate(R.layout.card_item, container, false);
ImageView imageView = (ImageView) view.findViewById(R.id.imageView);
Card card = cards.get(position);
imageView.setOnClickListener(card.onClick);
imageView.setImageResource(card.drawable);
container.addView(view);
return view;
}
Context context;
LayoutInflater layoutInflater;
List<Card> cards;
}
初始化:
public class MyActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
List<Card> cards = new ArrayList<>();
cards.add(new Card(this, ActivityProductList.class, R.drawable.product));
cards.add(new Card(this, ActivityEmployeeList.class, R.drawable.employee));
cards.add(new Card(this, ActivityCustomerList.class, R.drawable.customer));
HorizontalInfiniteCycleViewPager pager = findViewById(R.id.cycle);
pager.setAdapter(new InfiniteCycleViewPagerAdapter(this, cards));
Log.d("dashboard::oncreate", "dashboard");
}
}
PageAdapter
对象,为什么我的Log.d("instantiateItem", Integer.toString(position));
输出了这个:
instantiateItem: 0
instantiateItem: 2
instantiateItem: 1
instantiateItem: 1
instantiateItem: 2
我不明白为什么它的02112以及为什么它被称为5次?
Log.d("dashboard::oncreate", "dashboard");
?答案 0 :(得分:2)
您看到多次调用HorizontalInfiniteCycleViewPager
的事实很可能与Log.d("dashboard::oncreate", "dashboard");
的内部实施有关。
我会猜测并猜测它可能会实例化当前的“页面”,并将其他“页面”推断为两个“方向”。这样,如果向左滑动,您将在第1页登陆,如果向右滑动,则会在第2页登陆。
您在instantiateItem
之前看到对Looper
的调用,因为Android UI线程使用所谓的onCreate
(looper线程是非常常见的GUI实现方法)。
接下来会发生什么:
Looper
由UI线程onCreate
运行
pager.setAdapter(new InfiniteCycleViewPagerAdapter(this, cards))
期间,对ViewPager
的调用发生了Runnable
内的某处,有一个处理初始化的调用。此调用不是直接方法调用,而是向UI Looper
添加“初始化”Runnables
对象(添加Handler
的机制称为Runnable
)Looper
正在UI onCreate
内等待在其完成之前添加的所有其他工作。这项工作包括前面提到的Looper
Runnable
上的所有其他工作后,在UI线程上运行“初始化”Looper
如果您想深入了解Handler
,{{1}}和事件主题,我建议source。