Android開發listview選中高亮簡單實現程式碼分享

Android開發listview選中高亮簡單實現程式碼分享

百度了好幾種listview選中高亮的辦法都太繁瑣太不友好,我在無意中發現了一種簡單有效的辦法,而且程式碼量極少

原始碼如下:

MainActivity.java


package com.listviewtest;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
public class MainActivity extends Activity {
private ListView listview;
@Override   
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] items_text = { "選項一", "選項二", "選項三", "選項四", "選項五" };
listview = (ListView) findViewById(R.id.listView1);
listview.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,items_text));
listview.setOnItemClickListener(new OnItemClickListener() {
@Override   
public void onItemClick(AdapterView<?> arg0, View arg1,   
int position, long id) {
Drawable drawable=getResources().getDrawable(R.drawable.red);
listview.setSelector(drawable);
}
}
);
}
}

activity_main.xml


<pre name="code" class="html"><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=".MainActivity" > 
<ListView  
android:id="@ id/listView1"  
android:background="@color/gray" 
android:layout_width="match_parent"  
android:layout_height="wrap_content"  
android:scrollingCache="false"  
/>  
</RelativeLayout>

values/strings.xml中新增


<pre name="code" class="html"> <drawable name="red">#ff0000</drawable> 

總結