在列表视图中按位置编辑项目

Edit item by position in listview

大家好,我是一名新 android 开发人员。我尝试在点击后更改项目中的某些元素,这是我的代码

ListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                ImageView img = findViewById(R.id.imageView2);
                img.setImageResource(R.drawable.validate);
                TextView txtNumTicket, txtCaisse;
                txtNumTicket = findViewById(R.id.ref);
                txtCaisse = findViewById(R.id.textView);
                txtNumTicket.setTextColor(ContextCompat.getColor(Commande.this, R.color.bon));
                txtCaisse.setTextColor(ContextCompat.getColor(Commande.this, R.color.bon));
                Toast.makeText(getApplicationContext(), "You have selected item no."
                        + (i + 1) + "", Toast.LENGTH_SHORT).show();

            }
        });

当位置等于 6 时,我想 return 到初始状态(将图像更改为 R.id.novalidate 和彩色文本视图),我该怎么做?

评论后更新:

if (yourListView.getAdapter().getCount()  == 6) {
    img.setImageResource(R.drawable.novalidate);
    txtNumTicket.setTextColor(ContextCompat.getColor(Commande.this, R.color.your_new_colour));
    txtCaisse.setTextColor(ContextCompat.getColor(Commande.this, R.color.your_new_colour));
}

第二次更新: 基于 this answer,以下是如何在列表的特定位置获得视图

public View getViewByPosition(int pos, ListView listView) {
    final int firstListItemPosition = listView.getFirstVisiblePosition();
    final int lastListItemPosition = firstListItemPosition + listView.getChildCount() - 1;

    if (pos < firstListItemPosition || pos > lastListItemPosition ) {
        return listView.getAdapter().getView(pos, null, listView);
    } else {
        final int childIndex = pos - firstListItemPosition;
        return listView.getChildAt(childIndex);
    }
}

所以您可以通过拨打以下电话获得您想要的视图:

View view = getViewByPosition (number_of_the_view_you_want_to_change, name_of_your_listview);

然后绑定该项目的 textviews/imageviews (view.findViewById(...)) 并如上所述设置颜色和文本