【问题标题】:How to disable items in a List View?如何禁用列表视图中的项目?
【发布时间】:2011-02-09 09:07:14
【问题描述】:

我有一个列表视图,它通过数据库中的记录填充。 现在我必须让一些记录可见但无法选择, 我怎样才能做到这一点?

这是我的代码

public class SomeClass extends ListActivity { 
    private static List<String> products; 
    private DataHelper dh; 
    public void onCreate(Bundle savedInstanceState) { 
        dh = new DataHelper(this); 
        products = dh.GetMyProducts();  /* Returns a List<String>*/ 
        super.onCreate(savedInstanceState); 
        setListAdapter(new ArrayAdapter<String>(this, R.layout.myproducts, products)); 
        ListView lv = getListView();
        lv.setTextFilterEnabled(true); 
        lv.setOnItemClickListener( new OnItemClickListener() { 
            @Override 
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { 
                // TODO Auto-generated method stub 
                Toast.makeText(getApplicationContext(), ((TextView) arg1).getText(), Toast.LENGTH_SHORT).show(); 
            } 
        }); 
    } 
}

布局文件myproducts.xml如下:

<?xml version="1.0" encoding="utf-8"?> 
<TextView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:padding="10dp" 
    android:textSize="16sp"> 
</TextView>

【问题讨论】:

    标签: android android-widget listviewitem


    【解决方案1】:

    使您自己的 ArrayAdapter 子类具有 AreAllItemsEnabled() 返回 false,并定义 isEnabled(int position) 以针对数据集中的给定项目返回 true/false。

    【讨论】:

    • 小心这个解决方案。 BaseAdapter 的文档指出以下“如果指定位置的项目不是分隔符,则返回 true”。这意味着如果您返回 false,则该项目是分隔项目。有些手机可能不会在普通项目和分隔项目之间绘制 android:divider。
    • 这绝对是真的,我以前遇到过这个问题;我要么在行布局本身中包含一个分隔符并在 getView() 中显示/隐藏它,要么让项目启用但忽略对它们的点击并设置一个没有按下状态的背景,因此它们看起来不可点击。
    • 很好地放置“标题”分隔线,以便在您的列表中包含部分!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-20
    • 1970-01-01
    相关资源
    最近更新 更多