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

时间:2015-03-28 10:07:36

标签: java android

我在活动中有listview和edittext。关于选择一个项目 列表视图我可以使用它将其背景更改为diff颜色 '机器人:listselector&#39 ;.现在,我开始编辑文本。我立刻开始编辑 文本列表视图中所选项目的背景颜色更改为 默认。怎么预防这个?

<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="$" />

1 个答案:

答案 0 :(得分:0)

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);


    }

试试这个,对我来说它有用。

相关问题