【问题标题】:How to change the checkbox drawable of a ListView?如何更改 ListView 的可绘制复选框?
【发布时间】:2015-06-16 14:11:14
【问题描述】:

我是 Android 编程新手,因此我们将不胜感激!我有一个如图所示的 ListActivity:

public class BasicViews5Activity extends ListActivity {

String[] names;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ListView listView = getListView();
    listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
    listView.setTextFilterEnabled(true);

    names = getResources().getStringArray(R.array.names_array);
    setListAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_checked,names));
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    Toast.makeText(this,"You have selected " + names[position], Toast.LENGTH_SHORT).show();
}

}

如何更改 ListView 中 CheckBox 的可绘制对象?

我的 Xml 看起来像这样:

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button android:id="@+id/btn"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Show selected items"
        android:onClick="onClick"/>

    <ListView
        android:id="@+id/android:list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:button="@drawable/checked"/>


</LinearLayout>

【问题讨论】:

  • 你指的是图标吗?选中/未选中
  • 是的图标,选中/取消选中。

标签: android listview drawable


【解决方案1】:

您的问题已经有回复here

我不喜欢背景布局较暗时复选框默认图像的外观,因此我使用 xml 选择器对其进行了更改,以便在按钮中具有白色背景。

android:button="@drawable/selector_check"中需要选择器

【讨论】:

  • 感谢 webo80,如果我的 xml 中没有 ListView,这可能吗?我正在使用 ListActivity,所以我没有创建包含 ListView 的布局?
  • 好的,您使用的是 LIstView,但您必须使用 XML 来定义行、列表中的一项、带有复选框。或者您正在以编程方式创建项目布局?
  • 抱歉,我现在设置了一些 xml。我已将我的 XML 放在问题中,我是否还必须有一个自定义行 xml?有没有办法只从 ListView 元素中设置图标?
  • 我知道了 :D 非常感谢
【解决方案2】:

如果有其他新手遇到类似问题:

您有一个扩展 ListActivity 或 ListFragment 的类。内 onActivityCreated() 方法你需要设置列表Adapter:

 ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
 R.layout.rowlayout, R.id.label, values);

 setListAdapter(adapter);

在您的 rowlayout.xml 中,您需要一个带有 id 'label' 的 TextView,这将是 用你的“值”数组中的字符串填充。

在 rowlayout.xml 中,您需要一个带有按钮属性集的复选框:

android:button="@drawable/custom_checkbox_design"

在 custom_checkbox_design.xml 中,您需要以下内容:

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

<item android:drawable="@drawable/checked" android:state_checked="true"/>
<item android:drawable="@drawable/unchecked" android:state_checked="false"/>

</selector>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-06
    • 1970-01-01
    • 2016-04-01
    • 2018-01-12
    • 1970-01-01
    • 2016-11-17
    • 1970-01-01
    相关资源
    最近更新 更多