Android:如何在创建列表时禁用列表项 [英] Android: How to disable list items on list creation

查看:19
本文介绍了Android:如何在创建列表时禁用列表项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Android 开发还很陌生,仍然在做很多事情.

I'm pretty new to Android dev and still working out a lot of things.

我有一个显示使用以下代码的主菜单,但不知道如何禁用菜单中的选定项目.有人可以帮我提供一些示例代码吗?

I've got a main menu showing using the following code, but can't work out how to disable selected items in the menu. Can anybody help me with some sample code?

public class listTest extends ListActivity {

    @Override
    public void onCreate(Bundle savedState) {
        super.onCreate(savedState);
        setListAdapter(ArrayAdapter.createFromResource(this, R.array.mainMenu,
                android.R.layout.simple_list_item_1)); 
        //not sure how to disable list items here
    }

    protected void onListItemClick(ListView list, View view, int position, long id) {
        // can disable items when they are clicked on
        view.setEnabled(false);
    }   

}

并且我的 strings.xml 文件中有一个 string-array:

and I have a string-array in my strings.xml file:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="mainMenu">
        <item>Item 1</item>
        <item>Item 2</item>
        <item>Item 3</item>
    </string-array> 
</resources>

谢谢

推荐答案

为了在创建列表时禁用列表项,您必须从 ArrayAdapter 子类化.您必须覆盖以下方法:isEnabled(int position)areAllItemsEnabled().以前,您返回 truefalse 取决于是否启用给定位置的列表项.后者返回 false.

In order to disable list items on list creation you have to subclass from ArrayAdapter. You have to override the following methods: isEnabled(int position) and areAllItemsEnabled(). In former you return true or false depending is list item at given position enabled or not. In latter you return false.

如果你想使用 createFromResource() 你还必须实现那个方法,因为 ArrayAdapter.createFromResource() 仍然实例化 ArrayAdapter 而不是您自己的适配器.

If you want to use createFromResource() you will have to implement that method as well, since the ArrayAdapter.createFromResource() still instantiates ArrayAdapter instead of your own adapter.

最后,代码将如下所示:

Finally, the code would look something like the following:

class MenuAdapter extends ArrayAdapter<CharSequence> {

    public MenuAdapter(
            Context context, int textViewResId, CharSequence[] strings) {
        super(context, textViewResId, strings);
    }

    public static MenuAdapter createFromResource(
            Context context, int textArrayResId, int textViewResId) {

        Resources      resources = context.getResources();
        CharSequence[] strings   = resources.getTextArray(textArrayResId);

        return new MenuAdapter(context, textViewResId, strings);
    }

    public boolean areAllItemsEnabled() {
        return false;
    }

    public boolean isEnabled(int position) {
        // return false if position == position you want to disable
    }
}

这篇关于Android:如何在创建列表时禁用列表项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆