时间:2016-11-19 15:46:41

标签: android listview

关注this post我这样做:

在我的ListView中,我设置了所选项目的背景颜色,如下所示:

<ListView
   android:id="@+id/list_date"
   android:choiceMode="singleChoice"
   android:listSelector="#666666"
/>

当用户点击我的列表中的某个项目时,它会保持突出显示,很好。

现在我想在开始时预选(突出显示)列表中的项目。我尝试过:

list_date.performItemClick(list_date, 0, list_date.getItemIdAtPosition(0));

但不能工作。我怎么能这样做?

最终工作代码:

TextView txtv,txtv2;
arrayAdapter = new ArrayAdapter<String>(HistoryActivity.this, R.layout.row, R.id.textViewList, date) {
            public View getView(int position, View convertView, ViewGroup parent) {
                if (convertView == null) {
                    LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    convertView = inflater.inflate(R.layout.row, parent, false);
                }
                txtv = (TextView) convertView.findViewById(R.id.textViewList);
                txtv.setText(date.get(position));
                if(position == 0){
                    txtv.setBackgroundColor(Color.parseColor("#93581c"));
                    txtv2 = (TextView) convertView.findViewById(R.id.textViewList);
                }
                return convertView;
            }
        };

list_date.setAdapter(arrayAdapter);

    list_date.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {

            if (position!=0)
                    txtv2.setBackgroundColor(Color.TRANSPARENT);
            ........
            ........
        }
}

2 个答案:

答案 0 :(得分:1)

您可以在适配器中手动应用背景颜色:

arrayAdapter = new ArrayAdapter<String>(HistoryActivity.this, R.layout.row, R.id.textViewList, array) {
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = inflater.inflate(R.layout.R.layout.row, parent, false);
            }
            TextView tv = (TextView) convertView.findViewById(R.id.textViewList);
            tv.setText(array[position]);
            if(position == 0)
                tv.setBackgroundColor(Color.parseColor("#666666"));
            return convertView;
        }
    };

答案 1 :(得分:0)

为此,您可以使用saveInstanceState来保存状态。这是官方文档Follow Documentaion