我的程序和列表视图有问题。 我有2项上有一个简单的列表视图ListView儿童问题
李四
大卫琼斯
我想设置的第一个元素,以绿色的背景颜色,但我不断收到当我使用
namesList.getChildAt(0).setBackgroundColor(Color.GREEN);
也
一个空指针异常namesList.getChildCount();
总是返回0,即使列表中有2个项目。
我真的不明白为什么这不起作用,是否有一些步骤我错过了。
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是** **异步... getChildCount()等。最终将得到正确的值。改变颜色的地方在适配器本身:) – rupps
@rupps你是这个意思吗? ArrayAdapter适配器=新ArrayAdapter ( 此,android.R.layout.simple_list_item_1, 名); namesList.getChildAt(0).setBackgroundColor(Color.GREEN); namesList.setAdapter(adapter); ,这仍然不是为我工作不幸 –
user2950720