开发者

Can not get element from layout

开发者 https://www.devze.com 2023-02-09 02:33 出处:网络
I have 2 activities. The 2nd .xml looks like: <?xml version=\"1.0\" encoding=\"utf-8\"?> <LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"

I have 2 activities. The 2nd .xml looks like:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <ListView 
            android:id="@+id/TrainsListView"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" 
        />
</LinearLayout>

Part of manifest:

<activity android:na开发者_如何学JAVAme="TrainsActivity">

</activity>

And I'm trying to get TrainsListView:

mListView = (ListView) findViewById(R.id.TrainsListView);

But after this mlistView is null. Why?


I'm guessing this is happening in your Activity's onCreate() method because you are calling findViewById() before you have called setContentView(). If that's not the case then please show more of your code.


If findViewById() is failing to find your target id, here are some reasons this may happen:

[[ In your case, I suspect #1 or #2.]

  1. SetContentView() (or inflate) hasn't been called yet to associate a layout to search yet.

  2. SetContentView() (or inflate) was called with a layout that does not contain the target id, e.g. you specified the wrong layout.

  3. There's a typo in the id in the layout or in the code.

  4. You've imported the wrong R file (like a library component's R file) and coincidentally the same id was also used in the other R file).

  5. You're searching the wrong view, e.g. you inflated a menu layout and did not attach it to the root layout and then you attempted to search for an id in the root layout (findBiewById(..)) when you meant to search the inflated menu layout (menu.findBiewById(..)).

0

精彩评论

暂无评论...
验证码 换一张
取 消