【问题标题】:How to change background color of each row in list view?如何更改列表视图中每一行的背景颜色?
【发布时间】:2011-10-07 06:09:34
【问题描述】:

我的应用程序包含 1 个列表视图,数据源是 1 个 sqlite 表,当我长按列表视图中的任何行时,它将显示 1 个菜单选项来更改该行的颜色,为此我使用了 onContextItemSelected 函数,在选择菜单选项时,它将调用 1 个函数 change_color。我应该在 change_color 函数中写什么,以便我可以更改行 bg 颜色。

    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.add(0, PROCESSED_ID, 0, R.string.menu_processed);
    }



    public boolean onContextItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case PROCESSED_ID:
            AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
                    .getMenuInfo();

            change_color();
            return true;
        }
        return super.onContextItemSelected(item);
    }

【问题讨论】:

    标签: android android-listview


    【解决方案1】:

    将你的方法称为:

    change_color(pass_your_list_view, pass_selected_position_of_list_view);
    

    并将 change_color() 定义为:

    private void change_color(ListView listView, int position) {
        listView.getChildAt(position).setBackgroundColor(Color.BLACK);
    }
    

    希望这会有所帮助。

    已编辑

    定义一个变量一个位置

    public static int position;
    

    并将您的代码替换为

    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.add(0, PROCESSED_ID, 0, R.string.menu_processed);
    
        // Get the info on which item was selected
        AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
        // Retrieve the position at where you long pressed
        position = info.position;
    
    }
    
    
    
    public boolean onContextItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case PROCESSED_ID:
            AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
                    .getMenuInfo();
    
            change_color(getListView(), position);
            return true;
        }
        return super.onContextItemSelected(item);
    }
    

    【讨论】:

    • 感谢您的回答,但它在 listView.getChildAt(position).setBackgroundColor(Color.BLACK); 行显示 nullPointerexception;
    • 好的。你怎么称呼这个方法?给我看那条线。你是在扩展 ListActivity 还是 Activity?
    • 扩展 ListActivity。我正在调用与您显示的相同的函数,iam 使用 getSelectetItemPosition 和 getListView 函数来获取位置和 Listview ,这些函数在切换案例循环之前在 onContextItemSelected 函数中调用。 listview 的数据源是 1 个 sqlite 表
    • 不,位置值返回为 -1。我可以用 id 代替 position 吗?
    • 不,这是你长按的行的位置。我正在更新我的答案如何读取长按行的位置。等等……
    【解决方案2】:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-14
      • 1970-01-01
      • 2013-01-06
      相关资源
      最近更新 更多