Как изменить цвет элементов ListView в фокусе и щелчке
У меня есть список View в моем приложении (это макет xml):
<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/arrayList"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:textFilterEnabled="true"
android:scrollbars="vertical"
android:drawSelectorOnTop="true">
</ListView>
Каждый элемент моего списка View состоит из двух TextView:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout android:layout_width="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/row_container"
android:padding="5px" android:layout_height="wrap_content"
android:background="@color/white" android:shrinkColumns="0">
<TableRow>
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content" android:layout_below="@+id/
description"
android:id="@+id/description"
android:textColor="@color/black"
android:scrollHorizontally="true"
android:singleLine="true"></TextView>
</TableRow>
<TableRow>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/result"
android:textColor="@color/grey"
android:maxLines="1"
android:scrollHorizontally="true"></TextView>
</TableRow>
</TableLayout>
Я заполняю свой списокView из ArrayAdapter, таким образом:
public class Matches extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//set layout
setContentView(R.layout.list_layout);
// obtain reference to listview
ListView listView = (ListView) findViewById(R.id.arrayList);
ArrayAdapter<Match> arrayAdapter = new ArrayAdapter<Match>(
this, R.layout.custom_row, R.id.description, createItems()) {
@Override
public View getView (int position, View convertView, ViewGroup parent){
Match item = getItem (position);
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.custom_row, null);
TextView description = (TextView)rowView.findViewById(R.id.description);
TextView result = (TextView)rowView.findViewById(R.id.result);
description.setText(item.description + " Risultato: " + item.result );
result.setText(item.date + " " + item.hour);
return rowView;
}
};
listView.setAdapter(arrayAdapter);
Моя цель - изменить цвет текста и backgorund этих дочерних представлений всякий раз, когда выбран или нажат родитель.
Как я могу это сделать?
Ответы
Ответ 1
Представления child в строке списка должны рассматриваться как выбранные, когда выбрана родительская строка, поэтому вы должны просто установить нормальный режим рисования/списка цветов в представлениях, которые вы хотите изменить, не нужен беспорядочный Java-код, См. этот SO сообщение.
В частности, вы должны установить textColor
вашего textViews в XML-ресурс, подобный этому:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true" android:drawable="@color/black" /> <!-- focused -->
<item android:state_focused="true" android:state_pressed="true" android:drawable="@color/black" /> <!-- focused and pressed-->
<item android:state_pressed="true" android:drawable="@color/green" /> <!-- pressed -->
<item android:drawable="@color/black" /> <!-- default -->
</selector>
Ответ 2
В вашем main.xml включить в свой список ListView следующее:
android:drawSelectorOnTop="false"
android:listSelector="@android:color/darker_gray"
Ответ 3
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_pressed="true" android:drawable="@drawable/YOUR DRAWABLE XML" />
<item android:drawable="@drawable/YOUR DRAWABLE XML" />
</selector>
Ответ 4
Здесь хорошая статья о том, как использовать селекторы со списками.
Вместо того, чтобы устанавливать его как андроид: фон ListView, я считаю, что вы хотите установить android: listSelector, как показано ниже:
<ListView android:id="@+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:divider="@null"
android:dividerHeight="0dip"
android:listSelector="@drawable/list_selector" />
Ответ 5
listview.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(final AdapterView<?> parent, View view,
final int position, long id) {
// TODO Auto-generated method stub
parent.getChildAt(position).setBackgroundColor(getResources().getColor(R.color.listlongclick_selection));
return false;
}
});
Ответ 6
Очень старый, но я просто боролся с этим, вот как я решил его в чистом xml. В res/values /colors.xml я добавил три цвета (цвет _...);
<resources>
<color name="black_overlay">#66000000</color>
<color name="colour_highlight_grey">#ff666666</color>
<color name="colour_dark_blue">#ff000066</color>
<color name="colour_dark_green">#ff006600</color>
</resources>
В папке res/drawable я создал listview_colours.xml, который содержал:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/colour_highlight_grey" android:state_pressed="true"/>
<item android:drawable="@color/colour_dark_blue" android:state_selected="true"/>
<item android:drawable="@color/colour_dark_green" android:state_activated="true"/>
<item android:drawable="@color/colour_dark_blue" android:state_focused="true"/>
</selector>
В main_activity.xml найдите List List и добавьте drawable в listSelector;
<ListView
android:id="@+id/menuList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:listSelector="@drawable/listview_colours"
android:background="#ff222222"/>
</LinearLayout>
Играйте с состояниями _... элементов в listview_colours.xml, чтобы получить нужный эффект.
Существует также метод, в котором вы можете установить стиль представления списка, но мне никогда не удалось заставить его работать