突出显示列表视图项

3
我需要在触摸列表项时突出显示它并保持突出显示。我尝试了所有我找到的方法,但都没有起作用。这是我的代码:
这是列表视图:
<ListView
    android:id="@+id/lvUsers"
    android:layout_width="300dp"
    android:layout_height="fill_parent"
    android:layout_alignParentLeft="true"
    android:background="@drawable/border2"
    android:choiceMode="singleChoice"
    android:padding="5dp" >
</ListView>

@drawable/border2是列表视图周围的一个边框。

这是列表视图项的布局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layoutUsersRow"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/list_selector_background"
android:orientation="vertical" >

<TextView
    android:id="@+id/tvAllUsersName"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="10dp"
    android:text="User name"
    android:textAppearance="?android:attr/textAppearanceLarge" />

这是 list_selector_background:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true" android:drawable="@color/blue" /> <!-- focused -->
    <item android:state_focused="true" android:state_pressed="true" android:drawable="@color/blue" /> <!-- focused and pressed-->
    <item android:state_pressed="true" android:drawable="@color/blue" /> <!-- pressed -->
    <item android:drawable="@color/transparent" /> <!-- default -->
</selector>

这是来自列表视图适配器的代码。
public class UsersAdapter extends BaseAdapter implements OnClickListener {

LoginActivity context;
private List<String> listOfUsers;

public UsersAdapter(LoginActivity _context, List<String> listOfUsers) {
    context = _context;
    this.listOfUsers = listOfUsers;
}

public int getCount() {
    return listOfUsers.size();
}

public Object getItem(int position) {
    return listOfUsers.get(position);
}

public long getItemId(int position) {
    return position;
}

public View getView(int position, View convertView, ViewGroup parent) {
    String entry = listOfUsers.get(position);
    if (convertView == null) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.users_row, null);
    }

    TextView UserName = (TextView) convertView.findViewById(R.id.tvAllUsersName);
    UserName.setText(entry);

    LinearLayout LinLayout = (LinearLayout) convertView.findViewById(R.id.layoutUsersRow);
    LinLayout.setFocusableInTouchMode(false);
    LinLayout.setFocusable(false);
    LinLayout.setOnClickListener(this);

    return convertView;
}

public void onClick(View v) {
    // get the row the clicked button is in
    LinearLayout row = (LinearLayout) v;

    TextView child = (TextView) row.getChildAt(0);
    if (child.getText().toString().equals("Admin")) {
        Intent i = new Intent("com.vorteksed.checkinform.ADMINLOGINACTIVITY");
        i.putExtra("verificationFor", "ADMIN_LOGIN");
        context.startActivity(i);
    } else {
        context.userClicked(child.getText().toString());

        // focus the pin field after selecting user name from the list
        if (context.currentList != null) {
            context.etLoginPin.setVisibility(View.VISIBLE);
            context.tvPin.setVisibility(View.VISIBLE);
            context.etLoginPin.requestFocus();
            context.etLoginPin.setText("");
            InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(context.etLoginPin, 0);
        }
    }
}
}

这个不起作用。只有在按下时才会突出显示项目,一旦释放,高亮就消失了。

以下是解决方案

从列表项布局中删除android:background="@drawable/list_selector_background"这一行。选择器根本不需要。这是适配器的代码:

public class UsersAdapter extends BaseAdapter {

LoginActivity context;
private List<String> listOfUsers;
boolean[] arrBgcolor;
private int blue = Color.BLUE;
private int transparent = Color.TRANSPARENT;

public UsersAdapter(LoginActivity _context, List<String> listOfUsers) {
    context = _context;
    this.listOfUsers = listOfUsers;

    arrBgcolor = new boolean[listOfUsers.size()];
    resetArrbg();

}

private void resetArrbg() {
    for (int i = 0; i < arrBgcolor.length; i++) {
        arrBgcolor[i] = false;                  
    }
}

public int getCount() {
    return listOfUsers.size();
}

public Object getItem(int position) {
    return listOfUsers.get(position);
}

public long getItemId(int position) {
    return position;
}

public View getView(final int position, View convertView, ViewGroup parent) {
    String entry = listOfUsers.get(position);
    if (convertView == null) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.users_row, null);
    }


    TextView UserName = (TextView) convertView.findViewById(R.id.tvAllUsersName);
    UserName.setText(entry);

    LinearLayout LinLayout = (LinearLayout) convertView.findViewById(R.id.layoutUsersRow);
    LinLayout.setFocusableInTouchMode(false);
    LinLayout.setFocusable(false);
    LinLayout.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            handleClick(v, position);
        }
    });

    if (arrBgcolor[position])
        LinLayout.setBackgroundColor(blue);
    else 
        LinLayout.setBackgroundColor(transparent);

    return convertView;
}

public void handleClick(View v, int position) {
    LinearLayout row = (LinearLayout) v;

    resetArrbg();
    arrBgcolor[position] = true;
    notifyDataSetChanged();

    TextView child = (TextView) row.getChildAt(0);
    if (child.getText().toString().equals("Admin")) {
        Intent i = new Intent("com.vorteksed.checkinform.ADMINLOGINACTIVITY");
        i.putExtra("verificationFor", "ADMIN_LOGIN");
        context.startActivity(i);
    } else {
        context.userClicked(child.getText().toString());

        // focus the pin field after selecting user name from the list
        if (context.currentList != null) {
            context.etLoginPin.setVisibility(View.VISIBLE);
            context.tvPin.setVisibility(View.VISIBLE);
            context.etLoginPin.requestFocus();
            context.etLoginPin.setText("");
            InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(context.etLoginPin, 0);
        }
    }
}

}

看看这个链接,可能会有所帮助:https://dev59.com/HGoy5IYBdhLWcg3wa9Yj?rq=1 - Ankush
已经看过了,没有帮助。 - nikmin
2个回答

1
请移除选择器并尝试以下操作:

编辑

public class UsersAdapter extends BaseAdapter implements OnClickListener {

        LoginActivity context;
        private List<String> listOfUsers;
        boolean[] arrBgcolor;
        private int blue = Color.BLUE;

        public UsersAdapter(LoginActivity _context, List<String> listOfUsers) {
            context = _context;
            this.listOfUsers = listOfUsers;

            arrBgcolor = new boolean[listOfUsers.size()];
            resetArrbg();

        }

        private void resetArrbg() {
            for (int i = 0; i < arrBgcolor.length; i++) {
                arrBgcolor[i] = false;                  
            }
        }

        ......

        public View getView(final int position, View convertView, ViewGroup parent) {
            String entry = listOfUsers.get(position);
            if (convertView == null) {
                LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = inflater.inflate(R.layout.users_row, null);
            }


            TextView UserName = (TextView) convertView.findViewById(R.id.tvAllUsersName);
            UserName.setText(entry);

            LinearLayout LinLayout = (LinearLayout) convertView.findViewById(R.id.layoutUsersRow);
            LinLayout.setFocusableInTouchMode(false);
            LinLayout.setFocusable(false);
            LinLayout.setOnClickListener(this);

            //add the following, the position is accessible from here
            if (arrBgcolor[position]) {
                convertView.setBackgroundColor(blue);
            }
            convertView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    resetArrbg();
                    arrBgcolor[position] = true;
                    notifyDataSetChanged();
                }
            }); 
            return convertView;
        }

@mango 我已经处理了多选,但是滚动时重复选择怎么办? - nikmin
你的意思是什么?你的意思是选择发生在不同的位置吗?尝试使用上面编辑过的代码。 - mango
@Shakti,你是说如果我使用ArrayList而不是布尔列表,就可以解决重复问题? - nikmin
使用ArrayList不会让你变得更好,事实上它会更糟。你确定你正在使用上面精确的代码吗?你记得在convertView.setOnClickListener中调用resetArrbg();了吗?你在其他onClick事件中有任何其他的背景颜色代码吗?仔细检查一下,这应该不会发生。 - mango
@mango 是的,我正在使用完全相同的代码,我将其复制并粘贴到我的代码中。多选仍然存在,并且还有另一个问题...我的编辑文本框没有获得焦点,因为现在我点击的是转换视图而不是线性布局,所以线性布局的onClick不会被调用。我必须将两者都放在线性布局的click listener中。 - nikmin
显示剩余5条评论

0

////@drawable/list_selector

 <selector xmlns:android="http://schemas.android.com/apk/res/android">

  <item android:drawable="@drawable/list_item_bg_normal"
  android:state_pressed="false" android:state_selected="false" android:state_activated="false"/>

  <item android:drawable="@drawable/list_item_touch"
  android:state_pressed="true"/>

 <item android:drawable="@drawable/list_item_touch"
 android:state_pressed="false" android:state_selected="true"/>

 <item android:drawable="@drawable/list_item_bg_pressed"
  android:state_activated="true"/>

</selector>

////////////////////并且在ListView上

        <ListView
        android:id="@+id/list_slidermenu"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:choiceMode="singleChoice"
        android:dividerHeight="1dp"
        android:listSelector="@drawable/list_selector"
        android:background="@color/list_background"
        android:divider="#060606"/>

///////////////////////列表视图项

       <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:background="@drawable/list_selector">

      <ImageView
      android:id="@+id/icon"
      android:layout_width="35dp"
      android:layout_height="wrap_content"
      android:layout_alignParentLeft="true"
      android:layout_marginLeft="12dp"
      android:layout_marginRight="12dp"
      android:contentDescription="@string/desc_list_item_icon"
      android:src="@drawable/ic_home"
      android:layout_centerVertical="true" />

      </RelativeLayout>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接