当前位置:   article > 正文

listview选中高亮,选中栏目变颜色的一种最简单办法_android listview选中变色

android listview选中变色

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


源码如下:

MainActivity.java

  1. <pre name="code" class="java">package com.listviewtest;
  2. import android.os.Bundle;
  3. import android.app.Activity;
  4. import android.graphics.drawable.Drawable;
  5. import android.view.View;
  6. import android.widget.AdapterView;
  7. import android.widget.ArrayAdapter;
  8. import android.widget.ListView;
  9. import android.widget.AdapterView.OnItemClickListener;
  10. public class MainActivity extends Activity {
  11. private ListView listview;
  12. @Override
  13. protected void onCreate(Bundle savedInstanceState) {
  14. super.onCreate(savedInstanceState);
  15. setContentView(R.layout.activity_main);
  16. String[] items_text = { "选项一", "选项二", "选项三", "选项四", "选项五" };
  17. listview = (ListView) findViewById(R.id.listView1);
  18. listview.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,items_text));
  19. listview.setOnItemClickListener(new OnItemClickListener() {
  20. @Override
  21. public void onItemClick(AdapterView<?> arg0, View arg1,
  22. int position, long id) {
  23. Drawable drawable=getResources().getDrawable(R.drawable.red);
  24. listview.setSelector(drawable);
  25. }
  26. });
  27. }
  28. }

activity_main.xml
  1. <pre name="code" class="html"><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. xmlns:tools="http://schemas.android.com/tools"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. android:paddingBottom="@dimen/activity_vertical_margin"
  6. android:paddingLeft="@dimen/activity_horizontal_margin"
  7. android:paddingRight="@dimen/activity_horizontal_margin"
  8. android:paddingTop="@dimen/activity_vertical_margin"
  9. tools:context=".MainActivity" >
  10. <ListView
  11. android:id="@+id/listView1"
  12. android:background="@color/gray"
  13. android:layout_width="match_parent"
  14. android:layout_height="wrap_content"
  15. android:scrollingCache="false"
  16. />
  17. </RelativeLayout>


 
values/strings.xml中添加
<pre name="code" class="html"> <drawable name="red">#ff0000</drawable>  


 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/170803
推荐阅读
相关标签
  

闽ICP备14008679号