【问题标题】:Creating Buttons Programmatically in ViewPager instead of in XML在 ViewPager 中而不是在 XML 中以编程方式创建按钮
【发布时间】:2012-12-23 12:42:56
【问题描述】:

我希望在 ViewPager 中的视图上有左右按钮。不过,在第一个视图中,我只需要一个右键,而在最后一个视图中,我只需要一个左键。如何使用 ViewPager 和 PagerAdapter 以编程方式创建按钮?

似乎我无法在 PagerAdapter 的 instantiateItem 中执行此操作,这很糟糕,因为我只能在 PagerAdapter 代码中使用“位置”参数。

这是在我的onCreate中,rl是在Activity中全局声明的:

Button btnLeftClick = new Button(this);
btnLeftClick.setText("&lt&lt");
btnLeftClick.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT));

Button btnRightClick = new Button(this);
btnRightClick.setText("&gt&gt");
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。

有什么解决方法吗?

谢谢。

【问题讨论】:

    标签: android android-viewpager


    【解决方案1】:

    检查 rl 是否为空。 btnLeftClick 似乎还不错。

    【讨论】:

    • 哦,我明白了,是的,它是空的。你知道我是否可以在适配器中实例化和使用按钮?
    【解决方案2】:

    我从这个来源找到了答案:这个问题的答案就在这里:http://mobile.tutsplus.com/tutorials/android/android-user-interface-design-horizontal-view-paging/comment-page-1/#comment-14065

    我的问题是我必须首先参考按钮所在的布局才能使用findViewById

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-12
      • 2013-11-08
      • 1970-01-01
      • 2014-10-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多