【发布时间】:2012-12-23 12:42:56
【问题描述】:
我希望在 ViewPager 中的视图上有左右按钮。不过,在第一个视图中,我只需要一个右键,而在最后一个视图中,我只需要一个左键。如何使用 ViewPager 和 PagerAdapter 以编程方式创建按钮?
似乎我无法在 PagerAdapter 的 instantiateItem 中执行此操作,这很糟糕,因为我只能在 PagerAdapter 代码中使用“位置”参数。
这是在我的onCreate中,rl是在Activity中全局声明的:
Button btnLeftClick = new Button(this);
btnLeftClick.setText("<<");
btnLeftClick.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT));
Button btnRightClick = new Button(this);
btnRightClick.setText(">>");
btnRightClick.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT));
rl = (RelativeLayout) View.inflate(this, R.layout.view1, null);
这是我尝试在 PagerAdapter 中执行的操作,但出现 NullPointerException:
if (position == numViews) {
rl.addView(btnLeftClick);
}
如果我在 onCreate 中添加视图而不使用 if 语句,我不会得到 NullPointerException。
有什么解决方法吗?
谢谢。
【问题讨论】: