【发布时间】:2015-10-20 22:04:41
【问题描述】:
我的目的是在我垂直滑动时实现刷新。 主要是扩展一个FragmentActivty:
public class MainActivity extends FragmentActivity implements View.OnClickListener {
我也在 oncreate 内部创建一个 CustomViewPager:
private SwipeRefreshLayout swipeToRefresh;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this.getApplicationContext();
pager = new CustomViewPager(this, null);
pager.setId(R.id.pager);
pager.setPagingEnabled(false);
setContentView(pager);
这个pager是我在网上找到的一个例子。
问题是,如您所见,我正在声明一个 SwipeRefreshLayout,如果不从中获取 null,我就无法调用 findViewById。我已经检查了我的xml,没有编译错误,运行时只有nullpointerException。
swipeToRefresh = (SwipeRefreshLayout) findViewById(R.id.activity_main_swipe_refresh_layout);
swipeToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
我看到了一些关于它的主题,它们与我所坚持的非常接近,但它仍然没有用。 这是xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<android.support.v4.widget.SwipeRefreshLayout
android:id="@+id/activity_main_swipe_refresh_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</android.support.v4.widget.SwipeRefreshLayout>
</LinearLayout>
所以,我有两个问题:
- 我需要设置这个xml的内容视图吗?
- 为什么我得到 nullPointer?
任何问题都可以问,我有空。 谢谢。
【问题讨论】:
-
(1) 是,(2) 因为(1)
-
在 onCreate 中你似乎是
setContentView(pager),这意味着你的活动将只显示pager。如果要显示 xml 中的布局,则需要setContentView(R.layout.whatever_your_layout_is)。 Marcus 已经回答了您提出的问题。
标签: android xml nullpointerexception fragment findviewbyid