【发布时间】:2014-03-31 20:11:49
【问题描述】:
我的程序和列表视图有问题。 我有一个简单的列表视图,上面有 2 个项目
乔博客
大卫·琼斯
我正在尝试将第一个元素的背景颜色设置为绿色,但是在使用时我不断收到空指针异常
namesList.getChildAt(0).setBackgroundColor(Color.GREEN);
还有
namesList.getChildCount();
即使列表中有 2 项,也始终返回 0。
我真的不明白为什么这不起作用,我是否缺少某些步骤。
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Color;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class LecturerLogsView extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lecturer_logs_view);
ListView namesList = (ListView)findViewById(R.id.namesList);
String names[]={"Joe Bloggs", "David Jones"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this, android.R.layout.simple_list_item_1,
names);
namesList.setAdapter(adapter);
namesList.getChildAt(0).setBackgroundColor(Color.GREEN);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.lecturer_logs_view, menu);
return true;
}
}
xml文件
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".LecturerLogsView" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<ListView
android:id="@+id/namesList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1" >
</ListView>
</RelativeLayout>
【问题讨论】:
-
setAdapter 是 asynchronous ... getChildCount() 等。最终会得到正确的值。改变颜色的地方在适配器内部:)
-
@rupps 你是这个意思吗? ArrayAdapter
适配器 = new ArrayAdapter (this, android.R.layout.simple_list_item_1, names); namesList.getChildAt(0).setBackgroundColor(Color.GREEN); namesList.setAdapter(适配器); ,不幸的是,这仍然不适合我