Android:ListViewで選択したアイテムの背景色を変更します(実際の実行可能な方法!!!)



Android Change Background Color Selected Item Listview Real



記事のディレクトリ


1.インターフェースの効果

画像

2.ListViewが配置されているレイアウトファイルの背景色を灰色に設定します

<LinearLayout xmlns:android='http://schemas.android.com/apk/res/android' android:layout_width='match_parent' android:layout_height='match_parent' android:background='#ececec'> <ListView android:id='@+id/cxcxrs' android:layout_width='match_parent' android:layout_height='wrap_content'> ListView> LinearLayout>

3つ目は、ListViewが配置されているJavaファイルです。

//1. Set global variables in the class private int be_selected_item = 0 //The number of the selected item (for the selected item, change the background color) //2. In the data adapter of ListView, under the getView() method @Override public View getView(int position, View convertView, ViewGroup parent) { //By default, the background color of the first item becomes white if(position == 0){ convertView.setBackgroundColor(Color.parseColor('#ffffff')) } return convertView } //3. In the setOnItemClickListener listening event of ListView listView_left.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) { if(be_selected_item != position){ //Restore the original background color of the item selected last time adapterView.getChildAt(be_selected_item).setBackgroundColor(Color.parseColor('#ECECEC')) //The background color of the currently selected item becomes white view.setBackgroundColor(Color.parseColor('#ffffff')) //Refresh the number of the selected item be_selected_item = position } } })

4、追記

この機能を水平方向に見てください。
左右を見て、
上下を見て、
逆さまに見て、
どんなに見てもシンプルな感じです。
しかし、意外にも、私は午後中ずっと投げました。



インターネット上には多くの方法がありますが、期待した効果が得られません。
午後の探検を通して、
ついに、上記の方法を実現しました。

この方法は現実的で実行可能です。使用できない場合は、cxcxrs——自貢。