請參閱下面的代碼用於樣品活性ListViewGeneralSampleProjectActivity.java
public class ListViewGeneralSampleProjectActivity extends Activity {
private ListView sampleListView;
private static int save = -1;
int pos = 0;
MySimpleArrayAdapter adapter;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
"Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
"Linux", "OS/2","hai","Android", "iPhone", "WindowsMobile",
"Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
"Linux", "OS/2","hai","OS/2","hai", "Ubuntu", "Windows7", "Max OS X",
"Linux", "OS/2","hai","OS/2","hai" };
sampleListView=(ListView) findViewById(R.id.listView1);
adapter = new MySimpleArrayAdapter(this, values);
sampleListView.setAdapter(adapter);
sampleListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(),position+" Pressed", Toast.LENGTH_SHORT).show();
adapter.setCurrent(position);
adapter.notifyDataSetChanged();
}
});
}
}
MySimpleArrayAdapter.java
public class MySimpleArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
private int selected=0;
public MySimpleArrayAdapter(Context context, String[] values) {
super(context, R.layout.rowlayout, values);
this.context = context;
this.values = values;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.rowlayout, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.textView1);
textView.setText(values[position]);
if(position==selected)
{
rowView.setBackgroundColor(Color.RED);
}
return rowView;
}
public void setCurrent(int position) {
// TODO Auto-generated method stub
this.selected=position;
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
rowlayout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>