如何在列表视图中保留所选项目的背景色



我在一个活动中有一个listview和edittext。在中选择项目时列表视图我可以使用将其背景更改为不同的颜色android:listselector。现在,我开始编辑文本。我移动后立即进行编辑文本列表视图中所选项目的背景色更改为违约如何防止这种情况发生?

<ListView
    android:layout_width="wrap_content"
    android:layout_height="129dp"
    android:id="@+id/listView2"
    android:choiceMode="singleChoice"
    android:listSelector="#666666"
    android:layout_below="@+id/button7"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
   android:layout_marginTop="34dp" />
<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/editText"
    android:padding="-11dp"
    android:width="300dp"
    android:inputType="number"
    android:textSize="34sp"
    android:editable="true"
    android:layout_below="@+id/listView2"
    android:textStyle="bold"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="163dp"
    android:hint="$" />
public class Category_Adapter extends BaseAdapter {
    private Context context;
    private LayoutInflater inflater;
//initialize selectedposition
    private int selectedPosition = -1;

    public Category_Adapter(Context context, ArrayList<Category_Items> items,
            String show) {
        this.context = context;

            this.inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    }

    @Override
    public View getView(int position, View view, ViewGroup parent) {
        // TODO Auto-generated method stub
        if (view == null) {
            view = inflater.inflate(R.layout.category_titles_n_sellers_list,
                    parent, false);

        //Set Background to the selected position 
            if (position == selectedPosition) {
                view.setBackgroundColor(context.getResources().getColor(
                        R.color.orange_list));
                // view.setBackgroundColor(Color.parseColor("#FFA500"));
            } else {
                view.setBackgroundColor(context.getResources().getColor(
                        R.color.white));
                // view.setBackgroundResource(R.color.white);
            }

        return view;
    }
//get the selected position from activtiy
    public void setSelected(int position) {
        selectedPosition = position;
    }
}

现在在活动类:

@Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id) {
        // set the custom adapter method and set the selectedposition with the listview position
        ((Category_Adapter) adapter).setSelected(position);

    }

试试这个,对我来说很管用。

最新更新