如何在代码中选择listview中的第一项(使用baseadapter)来更改其背景

时间:2013-02-01 16:43:26

标签: android android-listview onclicklistener baseadapter

我的菜单列表视图包含baseadapter。

我的活动:

listView_menu = (ListView) findViewById(R.id.listView_menu);
model_category = new Model_Category(context);
listView_menu.setAdapter(new BaseAdapter_Menu(context, model_category.GetAllDifferentCategory()));
listView_menu.setOnItemClickListener(new OnItemClickListener() 
    {
        @Override
        public void onItemClick(AdapterView<?> arg0, View view, int position, long arg3)
        {
            view.setSelected(true);
        }
    });
listView_menu.setSelection(0);

我的BaseAdapter_Menu的getView方法(扩展BaseAdapter):

@Override
public View             getView(int position, View convertView, ViewGroup parent)
{
    View                rowView = convertView;

    if (rowView == null)
    {
        rowView = this.inflater.inflate(R.layout.customitemlistview_menu, null);
        ViewHolder viewHolder = new ViewHolder();
        viewHolder.category = (TextView) rowView.findViewById(R.id.category_menu);
        rowView.setTag(viewHolder);
    }
    ViewHolder holder = (ViewHolder)rowView.getTag();
    holder.category.setText(this.data.get(position));
    return (rowView);
}

每个项目都有一个背景选择器,根据其状态(SELECTED或NOT)有2个不同的背景。

当我点击列表视图中的某个项目时,我设置了我的视图item.setSelected("true")

因此,当我点击时,项目的背景会发生变化,但如何更改listview第一项的背景而不点击它。 我已经尝试了'listView_menu.setSelection(0)',但它不起作用。

4 个答案:

答案 0 :(得分:2)

我找到了解决方案! :)

在我的onCreate中我应用了这段代码:

listView_menu.setAdapter(new BaseAdapter_Menu(context, model_category.GetAllDifferentCategory()));
    listView_menu.setOnItemClickListener(new OnItemClickListener() 
    {
        @Override
        public void onItemClick(AdapterView<?> listView, View view, int position, long id)
        {
            ((BaseAdapter_Menu) listView_menu.getAdapter()).setPositionSelected(position);
        }
    });

在我的BaseAdater_Menu中:

我创建private int PositionSelected = 0;

我添加此方法

public void setPositionSelected(int position)
{
    PositionSelected = position;
    this.notifyDataSetChanged();
}

我重写了getView方法

public View getView(int position, View convertView, ViewGroup parent)
{
    View rowView = convertView;

    if (rowView == null)
    {
        rowView = this.inflater.inflate(R.layout.customitemlistview_menu, null);
        ViewHolder viewHolder = new ViewHolder();
        viewHolder.category = (TextView) rowView.findViewById(R.id.category_menu);
        rowView.setTag(viewHolder);
    }
    ViewHolder holder = (ViewHolder)rowView.getTag();
    holder.category.setText(this.data.get(position));
    if (position == PositionSelected)
        rowView.setBackgroundResource(R.drawable.item_menu_selected_background);
    else
        rowView.setBackgroundResource(R.drawable.item_menu_background);
    return (rowView);
}

感谢您的帮助:)

答案 1 :(得分:1)

编辑:

它是一个工作区,但我认为它有效:保存一个FisrtTime变量,它将在创建之后选择视图(在BaseAdapter_Menu上)

public BaseAdapter_Menu(...){
    ....
    mFirstTime = true;
    ....
}

public getView(int position, ...){
    .... // create your view

    if (mFirstTime && position == 0){
         mFirstTime = false;
         rootView.setSelected(true);
    }

    ... //Setup your view
}

答案 2 :(得分:0)

getView()方法中添加此代码:

if(position == 0) {
   rowView.setClickable(true);
   rowView.setSelected(true);
}

编辑:

您的Activity应该像这样实施OnItemClickListener

public class YourActivity extends Activity implements OnItemClickListener {

onCreate()方法中尝试此操作:

//after setting the onItemClickListener to your listView : 
listView_menu.setOnItemClickListener(this);
listView_menu.setSelection(0);
View firstView = listView_menu.getChildAt(0);
onItemClick(listView_menu, firstView, 0, -1);

并将方法onItemClick()提取到您的活动中:

@Override
public void onItemClick(AdapterView<?> arg0, View view, int position, long arg3) {
     view.setSelected(true);
}

答案 3 :(得分:0)

<强> RES /布局-V11 / cell.xml

如果您之后只需要开发API级别11的应用程序,那么您所要做的就是编写如下的xml代码。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="?android:attr/activatedBackgroundIndicator"
    android:orientation="vertical">
    <TextView 
        android:id="@+id/name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>
    <TextView 
        android:id="@+id/text"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>
</LinearLayout>

<强> RES /布局/ cell.xml

但是,在API级别&lt; = 10中,上面的代码会崩溃。所以它需要跟随......

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    <TextView 
        android:id="@+id/name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>
    <TextView 
        android:id="@+id/text"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>
</LinearLayout>

<强> DataListCursorAdapter.java

第二,需要通知您的适配器分配数据.// ...(a)

class DataListCursorAdapter extends CursorAdapter {
    private Listener mListener;
    public static class ViewHolder {
        public TextView name;
        public TextView text;
    }
    @SuppressWarnings("deprecation")
    public DataListCursorAdapter(Context context, Cursor c, Listener listener) {
        super(context, c);
        mListener = listener;
    }
    public DataListCursorAdapter(Context context, Cursor c, Listener listener, boolean autoRequery) {
        super(context, c, false);
        mListener = listener;
    }
    public DataListCursorAdapter(Context context, Cursor c, Listener listener, int flags) {
        super(context, c, FLAG_REGISTER_CONTENT_OBSERVER);
        mListener = listener;
    }
    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        try {
            ViewHolder holder = (ViewHolder) view.getTag();
            JSONObject json = new JSONObject(cursor.getString(cursor.getColumnIndex(Table.DATA)));
            final Data data = new Data(json);
            mListener.onDataAssigned(data, view);//...(a)

            holder.name.setText(data.name);
            holder.text.setText(data.text);
        }
        catch (JSONException e) {
        }
    }
    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.cell, null);
        ViewHolder holder = new ViewHolder();
        holder.name      = (TextView) view.findViewById(R.id.name);
        holder.text      = (TextView) view.findViewById(R.id.text);
        view.setTag(holder);
        return view;
    }
    public interface Listener {
        public void onDataAssigned(Data data, View view);//...(a)
    }
}

YourFragment.java或YourActivity.java

你实现了界面......

@Override
public void onDataAssigned(Data data, View view) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        return;
    }
    if (TextUtils.equals(mLastSelectedDataId, data.id)) {// default color
        view.setBackgroundColor(0xfff7aecb);
    }
    else {// selected color
        view.setBackgroundColor(0x00000000);
    }
}

您将所选项目保留在班级的字段上。

@Override
public void onItemClick(AdapterView<?> listView, View view, int position, long id) {
    Cursor cursor = mArrayCursorAdapter.getCursor();
    JSONObject json = new JSONObject(cursor.getString(cursor.getColumnIndex(Table.DATA)));
    final Data data = new Data(json);
    if (data != null && TextUtils.equals(mLastSelectedDataId, data.id)) {
        getListView().setItemChecked(position, false);
        mLastSelectedDataId = null;
    }
    else if (data != null) {
        getListView().setItemChecked(position, true);
        mLastSelectedDataId = data.id;
    }
}

重要

  • 在列表视图中,项目视图的数量不是项目的数量。
  • 所选视图(已更改颜色)将重复用于其他数据。

<强>更新

public class YourAdapter extends BaseAdapter {
    private LayoutInflater mInflater;
    private Listener mListener;
    private Model_Category mData;

    static class ViewHolder {
        TextView category;
    }
    public YourAdapter(Context context, Model_Category data, LayoutInflater inflater, Listener listener) {
        mInflater = inflater;
        mListener = listener;
        mData = data;
    }
    @Override
    public int getCount() {
        return /*return count*/;
    }
    @Override
    public Object getItem(int position) {
        return /*return item by position*/;
    }
    @Override
    public long getItemId(int position) {
        return /*return id by position*/;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        int type = getItemViewType(position);
        if (convertView == null){
            holder = new ViewHolder();
            convertView = mInflater.inflate(R.layout.customitemlistview_menu, null);
            holder.category = (TextView) convertView.findViewById(R.id.category_menu);
            convertView.setTag(holder);
        }
        else {
            holder = (ViewHolder) convertView.getTag();
        }
        mListener.onDataAssigned(mData.get(position), convertView);//...(a)
        holder.category.setText(mData.get(position));
        return convertView;
    }
    public interface Listener {
        public void onDataAssigned(Data data, View view);//...(a)
    }
}