Android ListView所选项目保持突出显示

我有XML两个ListView,一个包含一个由选择查询(lv_cli)填充的客户端列表,另一个包含选定的客户端的详细信息(lv_cli_det)。我想lv_clilv_cli_det显示细节的同时让客户保持选中状态。

XML:

<ListView

android:id="@+id/cli_lista"

android:layout_width="512dp"

android:layout_height="wrap_content"

android:fadeScrollbars="false"

>

</ListView>

<ListView

android:id="@+id/cli_lista_det"

android:layout_width="512dp"

android:layout_height="wrap_content"

android:layout_toRightOf="@+id/cli_lista"

android:fadeScrollbars="false" >

</ListView>

Java:

Cursor cursor = db.rawQuery("Select NrCl||';'||Nome From Clientes", null);

final ListView t = (ListView)findViewById(R.id.cli_lista);

ArrayAdapter<String> myarrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, listItems);

t.setAdapter(myarrayAdapter);

final ListView td = (ListView)findViewById(R.id.cli_lista_detalhe);

final ArrayAdapter<String> myarrayAdapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, listItems2);

t.setOnItemClickListener(new OnItemClickListener() {

@Override

public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

String item = ((TextView)view).getText().toString();

String[] strArray = item.split("\\;");

cli.load(strArray[0].toString());

td.setAdapter(myarrayAdapter2);

listItems2.clear();

listItems2.add("Nome: " + cli.getNome());

listItems2.add("Morada: " + cli.getMorada());

listItems2.add("Localidade: " + cli.getLoca());

listItems2.add("Código Postal: " + cli.getCp());

listItems2.add("Pais: " + cli.getPais());

listItems2.add("Nif: " + cli.getNif());

listItems2.add("Tel: " + cli.getTel());

listItems2.add("Tlm: " + cli.getTlm());

listItems2.add("Tipo Preço: " + cli.getTipoPvn());

listItems2.add("Cond. Pagamento: " + cli.getCpg());

listItems2.add("Obs: " + cli.getObs());

td.setAdapter(myarrayAdapter2);

myarrayAdapter2.notifyDataSetChanged();

}

});

回答:

若要在按下时保持列表视图项目的颜色,请在列表视图项目布局中包括以下行:

android:background="@drawable/bg_key"

然后bg_key.xml在这样的drawable文件夹中定义:

<?xml version="1.0" encoding="utf-8" ?>

<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item

android:state_selected="true"

android:drawable="@color/pressed_color"/>

<item

android:drawable="@color/default_color" />

</selector>

最后,将此包含在你的中ListView onClickListener

listView.setOnItemClickListener(new OnItemClickListener() {

@Override

public void onItemClick(AdapterView<?> parent, View view, int position,long arg3) {

view.setSelected(true);

... // Anything

}

});

这样,在任何时候都只能选择一项。你可以使用以下方式定义颜色值res/values/colors.xml:

<?xml version="1.0" encoding="utf-8"?>

<resources>

<color name="pressed_color">#4d90fe</color>

<color name="default_color">#ffffff</color>

</resources>

以上是 Android ListView所选项目保持突出显示 的全部内容, 来源链接: utcz.com/qa/411732.html

回到顶部