开发者

Android - findViewById(R.id.list) returns null

I have a class that开发者_JS百科 is called when my app launches.

public class MainActivity extends Activity implements NetworkEvent.

In this situation,

list = (ListView) findViewById(R.id.list);

works perfectly. However if I then call a new intent via:

   String[] names = object.names();

Intent myIntent = new Intent(MainActivity.this, SimpleList.class); myIntent.putExtra("names", names); startActivityForResult(myIntent, 0);

where SimpleList is defined as:

public class SimpleList extends ListActivity implements NetworkEvent

then when I call

   list=(ListView) findViewById(R.id.list);

Log.i("MyApp", "List:" + list);

from within the SimpleList class, list is null :(

How come? Both classes are within the same package.

Thanks.


I'm not exactly sure why it is happening in your case, but the ListView in your layout XML, must be defined as <ListView android:id="@android:id/list", not the typical <ListView android:id="@+id/list". If your class extends ListActivity, in that case, you just use getListView() to access the list.
Check out this: http://developer.android.com/reference/android/app/ListActivity.html


Make sure you call setContentView(R.whatever) before you can find any ids in it.


In a similar case, findViewById stopped working for me after adding a LinearLayout view.

The solution was to also add the following:

xmlns:android="http://schemas.android.com/apk/res/android"

to LinearLayout.


Add

"http://schemas.android.com/apk/res/android"

to your listView, for example:

<LinearLayout  
  xmlns:android="http://schemas.android.com/apk/res/android" 
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent">  

  <TextView 
    android:text="test"
    android:layout_width="fill_parent" 
    android:layout_height="40dp">
  </TextView>

  <ListView 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/list" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent">     
  </ListView>  

</LinearLayout>


I just want to mention what my problem was. In my XML, I had assigned android:name="@+id/bob" instead of android:id="@+id/bob", but because of the @+id, it was still registering it as an intellisensable field.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜