【问题标题】:Changing background color of list items in custom list view在自定义列表视图中更改列表项的背景颜色
【发布时间】:2012-11-27 16:29:42
【问题描述】:

我使用以下代码创建了一个自定义列表视图 ....但是此代码的问题是它只选择一个项目..但突出显示许多项目...我的意思是..例如..如果我有 8列表中的项目..我只能看到 3 个项目(其余的我必须滚动才能看到)..如果我单击第一个项目...它会与第四个和第 7 个项目一起突出显示...

public class MainMenu extends Activity {
    ListView lmenu;
    View v1;
    String s;
    Class<?> ourclass;
    View layout, row;
    static int trantype;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.menulist);

        Menu Menu_data[] = new Menu[] { new Menu("1.White"),
                new Menu("2.Blue"), new Menu("3.Purple"), new Menu("4.Red"),
                new Menu("5.Yellow"), new Menu("6.Black"), new Menu("6.Black"),
                new Menu("6.Black"), new Menu("6.Black"), new Menu("6.Black"),
                new Menu("6.Black"), new Menu("6.Black") };

        MenuAdapter adapter = new MenuAdapter(this, R.layout.menutext,
                Menu_data);
        lmenu = (ListView) findViewById(R.id.mainmenu);

        lmenu.setAdapter(adapter);

        lmenu.setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView<?> ada, View v, int position,
                    long id) {
                // TODO Auto-generated method stub

                /*
                 * v.setBackgroundColor(Color.parseColor("#FCD5B5")); if (!(v1
                 * == null) && v1 != v)
                 * v1.setBackgroundColor(Color.parseColor("#EEEEEE")); v1 = v;
                 */
                Intent swipeit = new Intent(getBaseContext(), Swipeit.class);
                trantype = position + 1;
                startActivity(swipeit);
            }
        });

        findViewById(R.id.BLogout).setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                // TODO Auto-generated method stub
                finish();
            }
        });
    }

    public class Menu {
        public String title;

        public Menu() {
            super();
        }

        public Menu(String title) {
            super();
            this.title = title;
        }
    }

    public class MenuAdapter extends ArrayAdapter<Menu> {

        Context context;
        int layoutResourceId;
        Menu data[] = null;
        LayoutInflater inflater;
        boolean[] arrBgcolor;
        private int activeHex, inactiveHex;

        public MenuAdapter(Context context, int layoutResourceId, Menu[] data) {
            super(context, layoutResourceId, data);
            this.layoutResourceId = layoutResourceId;
            this.context = context;
            this.data = data;
            activeHex = Color.parseColor("#FCD5B5");
            inactiveHex = Color.parseColor("#EEEEEE");

            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            arrBgcolor = new boolean[13];
        }

        @Override
        public View getView(final int position, final View convertView,
                ViewGroup parent) {
            try {
                MenuHolder holder = null;
                row = convertView;
                // convertView.setBackgroundColor(Color.BLACK);
                if (row == null) {
                    LayoutInflater inflater = ((Activity) context)
                            .getLayoutInflater();
                    row = inflater.inflate(layoutResourceId, parent, false);
                    holder = new MenuHolder();
                    holder.txtTitle = (TextView) row.findViewById(R.id.tv1);
                    row.setTag(holder);
                } else {
                    holder = (MenuHolder) row.getTag();
                }

                Menu Menu = data[position];
                holder.txtTitle.setText(Menu.title);
                holder.txtTitle.setOnClickListener(new OnClickListener() {

                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        resetArrbg();
                        arrBgcolor[position] = true;
                        if (arrBgcolor[position]) {
                            row.setBackgroundColor(activeHex);
                        } else {
                            row.setBackgroundColor(inactiveHex);
                        }
                        notifyDataSetChanged();
                    }
                });
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(), String.valueOf(e),
                        Toast.LENGTH_LONG).show();
            }
            return row;
        }

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

        public class MenuHolder {
            TextView txtTitle;
        }
    }
}

我的 xml 包含列表...

    <include
        android:id="@+id/header"
        android:layout_alignParentTop="true"
        layout="@layout/header" />

    <RelativeLayout
        android:id="@+id/Rlmain"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/header"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/TMain"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginBottom="8dp"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="8dp"
            android:text="Main Menu"
            android:textColor="#000000"
            android:textSize="15dp" />

        <View
            android:id="@+id/Vtop"
            android:layout_width="fill_parent"
            android:layout_height="2dp"
            android:layout_below="@+id/TMain"
            android:background="@android:color/darker_gray" />
    </RelativeLayout>

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_above="@+id/Vbot"
        android:layout_below="@+id/Rlmain"
        android:orientation="vertical" >

        <ListView
            android:id="@+id/mainmenu"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#E0E0E0"
            android:cacheColorHint="#00000000"
            android:divider="@android:color/transparent"
            android:dividerHeight="20dp" >
        </ListView>
    </RelativeLayout>

    <View
        android:id="@+id/Vbot"
        android:layout_width="fill_parent"
        android:layout_height="2dp"
        android:layout_above="@+id/textView1"
        android:background="@android:color/darker_gray" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:text="© India Transact Services Ltd."
        android:textColor="#000000"
        android:textSize="15dp" />

</RelativeLayout>

我的 xml 列表....

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/LLtv"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#EEEEEE"
    android:cacheColorHint="#00000000" >

    <TextView
        android:id="@+id/tv1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:paddingBottom="12dp"
        android:paddingTop="12dp"
        android:textColor="#000000"
        android:textSize="20dp" />

</LinearLayout>

谁能帮助我,告诉我哪里出错了?

【问题讨论】:

    标签: android


    【解决方案1】:

    目前的设置无法实现您想要的。您需要实现一个自定义适配器,您可以在其中访问 getView() 方法。由于答案here 中更清楚的原因,您需要做的是使用某种数据容器,该容器将使用某些指示器保存单个行的状态,然后根据它在容器上的位置执行您的操作(应该对应于它在列表视图上的位置)

    例如,看看这个重写:

    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
    
        resetArrbg();
        arrBgcolor[position] = true;
        if (arrBgcolor[position]) {
            v.setBackgroundColor(Color.parseColor("#FCD5B5"));
        } else {
            v.setBackgroundColor(Color.BLUE);           
        }
    }
    
    boolean[] arrBgcolor = new boolean[list.size()];
    
    private void resetArrbg() {
        for (int i = 0; i < arrBgcolor.length; i++) {
            arrBgcolor[i] = false;
        }
    }
    

    现在为什么它不能在当前设置下工作是否有意义?方法的else 部分,即影响其他视图的部分,永远不会发生,因为您无法访问onListItemClick 方法中的其他位置,但您可以在getView() 中访问。当然,除非您知道解决此问题的方法,否则无论如何,这对您来说都是更大的力量。尽管如此,我认为v1 技术对你没有任何好处。

    编辑:

    public class MainActivity extends Activity {
        ListView lmenu;
        View v1;
        String s;
        Class<?> ourclass;
        View layout, row;
        static int trantype;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            setContentView(R.layout.menulist);
    
            Menu Menu_data[] = new Menu[] { new Menu("1.White"),
                    new Menu("2.Blue"), new Menu("3.Purple"), new Menu("4.Red"),
                    new Menu("5.Yellow"), new Menu("6.Black"), new Menu("6.Black"),
                    new Menu("6.Black"), new Menu("6.Black"), new Menu("6.Black"),
                    new Menu("6.Black"), new Menu("6.Black") };
    
            MenuAdapter adapter = new MenuAdapter(this, R.layout.menutext, Menu_data);
            lmenu = (ListView) findViewById(R.id.mainmenu);
            lmenu.setAdapter(adapter);
        }
    
        public class Menu {
            public String title;
    
            public Menu() {
                super();
            }
    
            public Menu(String title) {
                super();
                this.title = title;
            }
        }
    
        public class MenuAdapter extends ArrayAdapter<Menu> {
    
            Context context;
            int layoutResourceId;
            Menu data[];
            LayoutInflater inflater;
            boolean[] arrBgcolor;
            private int activeHex, inactiveHex;
    
            public MenuAdapter(Context context, int layoutResourceId, Menu[] data) {
                super(context, layoutResourceId, data);
                this.layoutResourceId = layoutResourceId;
                this.context = context;
                this.data = data;
    
    
                activeHex = Color.parseColor("#FCD5B5");
                inactiveHex = Color.parseColor("#EEEEEE");
    
                inflater = (LayoutInflater) context
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                arrBgcolor = new boolean[data.length];
                resetArrbg();
            }
    
            @Override
            public View getView(final int position, final View convertView,
                    ViewGroup parent) {
    
                final MenuHolder holder;
                row = convertView;
                // convertView.setBackgroundColor(Color.BLACK);
                if (row == null) {
                    row = inflater.inflate(layoutResourceId, parent, false);
                    holder = new MenuHolder();
                    holder.txtTitle = (TextView) row.findViewById(R.id.tv1);
                    row.setTag(holder);
                } else {
                    holder = (MenuHolder) row.getTag();
                }
    
                Menu Menu = data[position];
                holder.txtTitle.setText(Menu.title);
    
    
                if (arrBgcolor[position]) {
                    row.setBackgroundColor(activeHex);
                } else {
                    row.setBackgroundColor(inactiveHex);
                }
    
                holder.txtTitle.setOnClickListener(new OnClickListener() {
    
                    public void onClick(View v) {
                        resetArrbg();
                        arrBgcolor[position] = true;
                        notifyDataSetChanged();
                    }
                });
    
                return row;
            }
    
            private void resetArrbg() {
                for (int i = 0; i < arrBgcolor.length; i++) {
                    arrBgcolor[i] = false;
                }
            }
    
            public class MenuHolder {
                TextView txtTitle;
            }
        }
    }
    

    【讨论】:

    • 好的...我更改了代码,现在我正在使用自定义数组适配器,如下所示“ezzylearning.com/tutorial.aspx?tid=1763429"...but 我很困惑在哪里调用 getview() 方法...如果我在 onCreate() 中的 onitemclick() 上调用它,那么它的参数应该是什么???
    • 您在自定义数组适配器中覆盖 getview 方法,就像您的教程一样。然后你在里面做一个点击监听器(最直接的方式),你把你的颜色更改代码放在里面。适配器将以这种方式完成所有操作,onitemclick 与它无关。您不调用 getview,每次加载新的 listview 行时都会自动调用它。如果您没有看到任何更改,也不要忘记 notifydatasetchanged()。
    • 没有人还是同样的问题...我已经更新了我的代码...对吗???还是我还是做错了?
    • 那么 logcat 说了什么?
    • 我修复了强制关闭...但它有同样的问题,即突出显示多行...它是 onclicktext...如果我们单击背景它不起作用... .所以还有更多想法:/
    【解决方案2】:

    这是因为 ListView 在填充列表时重用视图的方式。假设您在任何给定时间看到列表的三行。您通过设置背景颜色“突出显示”第一行(就像您一样),然后向下滚动。当第一行离开屏幕时,Android 会做一些聪明的事情。它不是为第五行创建新视图,而是重用第一行的视图。那是您更改背景颜色的视图,因此第五行现在具有相同的背景颜色。仅更改数据。

    至于如何在选中的行上实现不同的背景颜色,并且只在选中的行上,看看这个answer。我相信你必须实现一个自定义 ListAdapter,至少如果你正在为低于 11 的 API 级别进行开发。

    【讨论】:

      猜你喜欢
      • 2016-01-15
      • 1970-01-01
      • 2015-01-13
      • 2013-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多