gpt4 book ai didi

android - 自定义单选 ListView

转载 作者:IT王子 更新时间:2023-10-28 23:26:46 29 4
gpt4 key购买 nike

我想制作一个自定义 ListView ,在一行中有两个 TextView 和一个单选按钮。在 listitem 单击单选按钮状态应该是切换。我不能在这里使用简单适配器。

我已经问过这个问题了Single choice ListView custom Row Layout但没有找到任何令人满意的解决方案。

我目前正在做的是使用 simple_list_item_single_choice 并将两个 TextView 的数据放在一个由一些空格分隔的单个 View 中。但这里情况变得更糟(如下图所示)。

http://db.tt/ulP6pn7V

我想要的是固定大小和价格的位置,并将 ListView 作为单一选择。

列表的 XML 布局可以是:

**<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="horizontal" >

<TextView
android:id="@+id/tv_size"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:textSize="15sp"
android:width="200dp" />

<TextView
android:id="@+id/tv_price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:textSize="15sp"
android:width="70dp" />

<RadioButton
android:id="@+id/radioButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

</LinearLayout>**

如何为此制作自定义适配器?

最佳答案

我有类似的情况,但很容易解决。试试这个:

  1. 扩展 ListActivity 并设置您的自定义列表适配器

    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE); //if you need title to be hidden
    setContentView(R.layout.activity_add_to_cart_select_service_plan);
    setListAdapter(adapter);
    }
  2. 创建一个字段来存储适配器中选定的索引位置

    int selectedIndex = -1;
  3. 为其提供接口(interface)

    public void setSelectedIndex(int index){
    selectedIndex = index;
    }
  4. 根据 getView() 中选择的索引将选中状态设置为 true 或 false

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
    RadioButton rbSelect = (RadioButton) convertView
    .findViewById(R.id.radio1);
    if(selectedIndex == position){
    rbSelect.setChecked(true);
    }
    else{
    rbSelect.setChecked(false);
    }
    }
  5. 将单选按钮的可聚焦和可点击属性设置为“false”

     <RadioButton
    android:id="@+id/radio1"
    android:checked="false"
    android:focusable="false"
    android:clickable="false"
    />
  6. 将 listview descendantFocusability 属性设置为 'beforeDescendants'

    <ListView
    android:id="@android:id/list"
    android:choiceMode="singleChoice"
    android:descendantFocusability="beforeDescendants"
    />
  7. 覆盖 onListItemClick

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);
    adapter.setSelectedIndex(position);
    adapter.notifyDataSetChanged();
    }

就是这样..运行并检查

关于android - 自定义单选 ListView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8337180/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com