我有一个 Adroid Activity,我想介绍一个自定义列表视图。这是我的 onCreate() 活动方法。
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LoadListView();
ListView lvw = (ListView)findViewById(android.R.id.list);
lvw.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// selected item
String element = ((TextView) view).getText().toString();
// Launching new Activity on selecting single List Item
Intent i = new Intent(getApplicationContext(), AddEntryActivity.class);
// sending data to new activity
i.putExtra("entryToEdit", element);
long idToEdit = Long.parseLong(hEntries.get(position).toString());
i.putExtra("idToEdit", idToEdit);
startActivity(i);
}
});
DbAccess oDb = new DbAccess(this);
}
如您所见,调用 LoadListView() 方法来加载列表视图项:
private void LoadListView()
{
oDb = new DbAccess(this);
oDb.open();
List<cAttivita> entries = oDb.getAttivita();
CustomListAdapter listAdapter = new CustomListAdapter(MainActivity.this, android.R.layout.simple_list_item_1 , entries);
ListView lvwAttivita = (ListView)findViewById(android.R.id.list);
lvwAttivita.setAdapter(listAdapter);
hEntries = new HashMap();
for(int i = 0; i < entries.size(); i++)
{
hEntries.put(i, entries.get(i).getId());
}
}
自定义列表适配器类:
public CustomListAdapter(Context context, int textViewResourceId , List<cAttivita> list )
{
super(context, textViewResourceId, list);
mContext = context;
id = textViewResourceId;
items = list ;
}
@Override
public View getView(int position, View v, ViewGroup parent)
{
View mView = v ;
if(mView == null){
LayoutInflater vi = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mView = vi.inflate(id, null);
}
TextView text = (TextView) mView.findViewById(R.id.textView);
if(items.get(position) != null )
{
text.setTextColor(Color.WHITE);
text.setText(items.get(position).toString());
text.setBackgroundColor(Color.RED);
int color = Color.argb( 200, 255, 64, 64 );
text.setBackgroundColor( color );
}
return mView;
}
这是 activity_main.xml 代码:
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/textView"
android:textSize="20px"
android:paddingTop="10dip"
android:paddingBottom="10dip"/>
<ListView xmlns:android="schemas.android.com/apk/res/android";
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Attività"/>
问题在于:
TextView text = (TextView) mView.findViewById(R.id.textView);
为什么文本返回null?