Android开发listview选中高亮简单实现代码分享

2020-10-31 16:39:22 浏览数 (1)

百度了好几种listview选中高亮的办法都太繁琐太不友好,我在无意中发现了一种简单有效的办法,而且代码量极少

源码如下:

MainActivity.java

代码语言:javascript复制
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

代码语言:javascript复制
<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中添加

代码语言:javascript复制
<pre name="code" class="html"  <drawable name="red" #ff0000</drawable  

总结

以上就是本文关于Android开发listview选中高亮简单实现代码分享的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站:

android listview初步学习实例代码

android listview进阶实例分享

如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

0 人点赞