【问题标题】:Android Studio - How do I highlight the selected grid item, and un-highlight all others?Android Studio - 如何突出显示选定的网格项,并取消突出显示所有其他项?
【发布时间】:2016-04-11 16:25:56
【问题描述】:

我有一个由许多项目组成的网格。我希望用户能够单击网格中的项目;然后应突出显示该项目。如果随后单击其他项目,则应取消突出显示原始项目并突出显示新项目。

每个框都是一个TextView,具有不同的背景颜色。我不知道如何突出显示,所以目前我在框中放了一个“X”。我的问题是如何删除任何以前设置的 X。

到目前为止,这是我的代码(patternColour 只是一个具有名称和十六进制代码的对象):

coloursGrid = (GridView) findViewById(R.id.gridViewColoursGrid);
patternColourAdapter = new PatternColourAdapter(this, R.layout.colour_grid_layout, gridItemsColours);
coloursGrid.setAdapter(patternColourAdapter);
coloursGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        // Highlight selected colour, and unhighlight all others
        TextView unselected;
        for(int ii=0; ii<parent.getCount(); ii++) {
            unselected = ????; // Don't know what to put here!
            unselected.setText("");
        }
        TextView selected = (TextView) view;
        selected.setText("X");
    }
});

无论我用什么方法代替问号,我都会遇到错误(构建失败,或者应用程序此时崩溃)。

如何遍历所有 TextView 并取消设置所有文本?

【问题讨论】:

    标签: java android-studio


    【解决方案1】:

    您可以将GridView的choiceMode设置为singleChoice

    android:choiceMode="singleChoice"
    

    然后将网格视图项布局设置为可绘制的状态背景,如下所示:

    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:drawable="@color/green" android:state_pressed="true"></item>
        <item android:drawable="@color/green" android:state_activated="true"></item>
        <item android:drawable="@android:color/transparent"></item>
    </selector>
    

    【讨论】:

    • 谢谢。我认为,choiceMode 设置是我所缺少的!我决定用不同的方式进行着色,使用图像 - 当我再次查看我想要实现的目标时,我认为它会看起来更好。感谢您的帮助!
    【解决方案2】:
     coloursGrid.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
    
    coloursGrid.setOnItemSelectedListener(new OnItemSelectedListener()
        {
    
            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                    int arg2, long arg3) {
                // TODO Auto-generated method stub
                coloursGrid.setSelection(arg2)
    
            }
    
            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub
    
            }
    
    });
    

    它可能对你有帮助。

    【讨论】:

    • 感谢您的帮助!
    猜你喜欢
    • 2011-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-08
    相关资源
    最近更新 更多