点击时创建与ListView的行选择行/换背景颜色的ListView [英] Create a ListView with selectable rows/change background color of ListView rows when clicked

查看:151
本文介绍了点击时创建与ListView的行选择行/换背景颜色的ListView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题

我试图创建一个的ListView 与可选项目。我希望能够点击的的ListView项目,并具有项目改变颜色列表中,然后继续做别的事情的数据行。

我使用了一个 SimpleAdapter

我如何使它所以,当我点击一个行,它会变成不同的颜色,然后当我点击一个不同的行,新行被选中,变成一种新的颜色,和旧的行更改恢复正常?

code

下面是我的code为止。该的DBTools 类是拥有一切,我要显示在我的的ListView数据组织和照顾。该 getAllReceivers()方法返回一个的ArrayList 的HashMap<字符串,字符串> s表示有我所有的数据。

MainActivity.java:

 公共类MainActivity扩展ListActivity {
    DBTool中的DBTools =新的DBTools(本);

    ArrayList的< HashMap的<字符串,字符串>> receiverList;

    @覆盖
    保护无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        getActionBar()隐藏()。
        的setContentView(R.layout.activity_main);

        receiverList = dbTools.getAllReceivers();
        dbTools.close();
        ListView控件的ListView = getListView();
        如果(receiverList.size()!= 0){

            SimpleAdapter适配器=新SimpleAdapter(MainActivity.this,receiverList,R.layout.receiver_entry,新的String [] {receiverId,receiverName,完整路径},新的INT [] {R.id.receiverId,R.id .receiverName,R.id.fullPath});
            setListAdapter(适配器);
        }
    }
}
 

activity_main.xml:

 < XML版本=1.0编码=UTF-8&GT?;

< TableLayout的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    机器人:layout_width =match_parent
    机器人:layout_height =match_parent>

    <的TableRow
        机器人:layout_width =match_parent
        机器人:layout_height =WRAP_CONTENT
        机器人:背景=@机器人:彩色/黑白>

        <的TextView
            机器人:ID =@ + ID / titleTextView
            机器人:layout_width =WRAP_CONTENT
            机器人:layout_height =WRAP_CONTENT
            机器人:重力=center_horizo​​ntal
            机器人:文本=我的列表/>

    < /的TableRow>

        <的ListView
            机器人:layout_width =match_parent
            机器人:layout_height =match_parent
            机器人:背景=@机器人:彩色/黑白
            机器人:ID =@机器人:ID /列表/>

< / TableLayout>
 

receiver_entry.xml

 < XML版本=1.0编码=UTF-8&GT?;
<的TableRow的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    机器人:layout_width =FILL_PARENT
    机器人:layout_height =WRAP_CONTENT
    机器人:ID =@ + ID / tablerow的>

    <的TextView
        机器人:ID =@ + ID / receiverId
        机器人:layout_width =FILL_PARENT
        机器人:layout_height =WRAP_CONTENT
        机器人:能见度=水涨船高/>

    <的TextView
        机器人:ID =@ + ID / receiverName
        机器人:layout_width =WRAP_CONTENT
        机器人:layout_height =WRAP_CONTENT
        机器人:文本=Robotronics/>

    <的TextView
        机器人:ID =@ + ID / FULLPATH
        机器人:layout_width =WRAP_CONTENT
        机器人:layout_height =WRAP_CONTENT
        机器人:文本=123.45.678.910:8088/robtrox/find/>


< /的TableRow>
 

解决方案

解决方案

的解决这个问题是非常简单的。我们需要添加一个 OnItemClickListener 我们的的ListView 监听点击和作出相应的反应。

所以,在的onCreate()方法,一旦你确信你设置的数据不为空,你会想覆盖 onItemClick()方法监听点击,改变颜色。你也将要跟踪哪些项目,您选择的后续步骤,所以加公众诠释selectionId = -1; 在你的班上名列前茅。此外,你需要让 ListAdapter 知道你通过调用((SimpleAdapter)getListAdapter())改变了一些东西。notifyDataSetChanged()

 如果(receiverList.size()!= 0){
    listView.setOnItemClickListener(新AdapterView.OnItemClickListener(){

        @覆盖
        公共无效onItemClick(适配器视图<>适配器视图,视图中查看,INT指数,长ID){
            view.setBackgroundColor(Color.RED);
            TextView的receiverIdTextView =(TextView中)view.findViewById(R.id.receiverId);
            selectionId = Integer.valueOf(receiverIdTextView.getText()的toString());
            ((SimpleAdapter)getListAdapter())notifyDataSetChanged()。
         }

    });
    SimpleAdapter适配器= getNewAdapter();
    setListAdapter(适配器);

}
 

太棒了!现在我们有一个工作系统,该系统将改变你轻点行的颜色。但是,我们还没有完成。我们需要确保previous选择变回了正常的颜色。

对于这一点,我们将使用覆盖 SimpleAdapter getView()的方法,这就是所谓的每次的的ListView 去绘制项目正在显示它。

它实际上只显示它需要的物品 - 那些你可以看到。它不会呈现高于或低于屏幕的人。所以,如果你有200个项目在的ListView ,只有5或6,这取决于你的屏幕尺寸和项目的大小,都被渲染的时间。

要覆盖 getView()的方法,去到那里你初始化适配器,改变code到这一点:

  SimpleAdapter适配器=新SimpleAdapter(MainActivity.this,receiverList,R.layout.receiver_entry,新的String [] {receiverId,receiverName,完整路径},新INT [] {R.id.receiverId,R.id.receiverName,R.id.fullPath}){
    @覆盖
    公共查看getView(INT位置,查看convertView,ViewGroup中父){
        查看查看= super.getView(位置,convertView,父母);
        TextView的receiverIdTextView =(TextView中)view.findViewById(R.id.receiverId);
        如果(receiverIdTextView.getText()的toString()。等于(将String.valueOf(selectionId))){
            view.setBackgroundColor(Color.RED);
        } 其他 {
            view.setBackgroundColor(Color.WHITE);
        }
        返回查看;
    }
};
 

每一次行之一被绘制,因为 getView()将被调用,在的ListView 将检查当前的视图有排你选择的ID。如果不是这样,它会改变背景颜色为白色。如果是的话,它会改变背景颜色为红色。

和瞧!而已!现在,你是设置背景颜色为红色,当你点击了的ListView项目

最后code

MainActivity.java:

 公共类MainActivity扩展ListActivity {
    DBTool中的DBTools =新的DBTools(本);

    ArrayList的< HashMap的<字符串,字符串>> receiverList;

    @覆盖
    保护无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        getActionBar()隐藏()。
        的setContentView(R.layout.activity_main);

        receiverList = dbTools.getAllReceivers();
        dbTools.close();
        ListView控件的ListView = getListView();
        如果(receiverList.size()!= 0){
            listView.setOnItemClickListener(新AdapterView.OnItemClickListener(){

                @覆盖
                公共无效onItemClick(适配器视图<>适配器视图,视图中查看,INT指数,长ID){
                    view.setBackgroundColor(Color.RED);
                    TextView的receiverIdTextView =(TextView中)view.findViewById(R.id.receiverId);
                    selectionId = Integer.valueOf(receiverIdTextView.getText()的toString());
                    ((SimpleAdapter)getListAdapter())notifyDataSetChanged()。
                 }

            });

            SimpleAdapter适配器=新SimpleAdapter(MainActivity.this,receiverList,R.layout.receiver_entry,新的String [] {receiverId,receiverName,完整路径},新的INT [] {R.id.receiverId,R.id .receiverName,R.id.fullPath}){
                @覆盖
                公共查看getView(INT位置,查看convertView,ViewGroup中父){
                    查看查看= super.getView(位置,convertView,父母);
                    TextView的receiverIdTextView =(TextView中)view.findViewById(R.id.receiverId);
                    如果(receiverIdTextView.getText()的toString()。等于(将String.valueOf(selectionId))){
                        view.setBackgroundColor(Color.RED);
                    } 其他 {
                        view.setBackgroundColor(Color.WHITE);
                    }
                    返回查看;
                }
            };
            setListAdapter(适配器);
        }
    }
}
 

activity_main.xml:

 < XML版本=1.0编码=UTF-8&GT?;

< TableLayout的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    机器人:layout_width =match_parent
    机器人:layout_height =match_parent>
    <的TableRow
        机器人:layout_width =match_parent
        机器人:layout_height =WRAP_CONTENT
        机器人:背景=@机器人:彩色/黑白>

        <的TextView
            机器人:ID =@ + ID / titleTextView
            机器人:layout_width =WRAP_CONTENT
            机器人:layout_height =WRAP_CONTENT
            机器人:重力=center_horizo​​ntal
            机器人:文本=我的列表/>

    < /的TableRow>

        <的ListView
            机器人:layout_width =match_parent
            机器人:layout_height =match_parent
            机器人:背景=@机器人:彩色/黑白
            机器人:ID =@机器人:ID /列表/>
< / TableLayout>
 

receiver_entry.xml

 < XML版本=1.0编码=UTF-8&GT?;
<的TableRow的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    机器人:layout_width =FILL_PARENT
    机器人:layout_height =WRAP_CONTENT
    机器人:ID =@ + ID / tablerow的>

    <的TextView
        机器人:ID =@ + ID / receiverId
        机器人:layout_width =FILL_PARENT
        机器人:layout_height =WRAP_CONTENT
        机器人:能见度=水涨船高/>

    <的TextView
        机器人:ID =@ + ID / receiverName
        机器人:layout_width =WRAP_CONTENT
        机器人:layout_height =WRAP_CONTENT
        机器人:文本=Robotronics/>

    <的TextView
        机器人:ID =@ + ID / FULLPATH
        机器人:layout_width =WRAP_CONTENT
        机器人:layout_height =WRAP_CONTENT
        机器人:文本=123.45.678.910:8088/robtrox/find/>

< /的TableRow>
 

Problem

I'm trying to create a ListView with selectable items. I want to be able to click on an item in the ListView and have the item change color in the list, and then go on and do something else with the data from the row.

I'm using a SimpleAdapter.

How do I make it so that when I tap on a row, it turns a different color, and then when I tap on a different row, the new row is selected and changed to a new color, and the old row changes back to normal?

Code

Here is my code so far. The DBTools class is has all of the data that I want to be displayed in my ListView organized and taken care of. The getAllReceivers() method returns an ArrayList of HashMap<String, String>s that have all of my data.

MainActivity.java:

public class MainActivity extends ListActivity {
    DBTools dbTools = new DBTools(this);

    ArrayList<HashMap<String, String>> receiverList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getActionBar().hide();
        setContentView(R.layout.activity_main);

        receiverList = dbTools.getAllReceivers();
        dbTools.close();
        ListView listView = getListView();
        if(receiverList.size() != 0) {

            SimpleAdapter adapter = new SimpleAdapter(MainActivity.this,receiverList, R.layout.receiver_entry, new String[] {"receiverId","receiverName", "fullPath"}, new int[] {R.id.receiverId, R.id.receiverName, R.id.fullPath});
            setListAdapter(adapter);
        }
    }
}

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/black" >

        <TextView
            android:id="@+id/titleTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:text="My List" />

    </TableRow>

        <ListView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@android:color/black"
            android:id="@android:id/list" />

</TableLayout>

receiver_entry.xml

<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/tableRow" >

    <TextView
        android:id="@+id/receiverId"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:visibility="gone" />

    <TextView
        android:id="@+id/receiverName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Robotronics" />

    <TextView
        android:id="@+id/fullPath"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="123.45.678.910:8088/robtrox/find" />


</TableRow>

解决方案

Solution

The solution to this problem is very simple. We need to add an OnItemClickListener to our ListView to listen for clicks and respond accordingly.

So, in the onCreate() method, once you've made sure that you set of data isn't empty, you're going to want to Override the onItemClick() method to listen for the click and change the color. You're also going to want to keep track of which item you selected for the later steps, so add public int selectionId = -1; at the top of your class. Furthermore, you'll need to let the ListAdapter know that you changed something by calling ((SimpleAdapter) getListAdapter()).notifyDataSetChanged().

if(receiverList.size() != 0) {
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int index, long id) {
            view.setBackgroundColor(Color.RED);
            TextView receiverIdTextView = (TextView) view.findViewById(R.id.receiverId);
            selectionId = Integer.valueOf(receiverIdTextView.getText().toString());
            ((SimpleAdapter) getListAdapter()).notifyDataSetChanged();
         }

    });
    SimpleAdapter adapter = getNewAdapter();
    setListAdapter(adapter);

}

Great! Now we have a working system that will change the color of the row that you tap. But we're not done yet. We need to make sure that the previous selection changes back to the normal color.

For this, we are going to use override the SimpleAdapter's getView() method, which is called everytime the ListView goes to draw the items being displayed in it.

It only actually displays the items it needs to - the ones that you can see. It does not render the ones above or below your screen. So if you have 200 items in a ListView, only 5 or 6, depending on the size of your screen and the size of the items, are being rendered at a time.

To override the getView() method, go up to where you initialize the adapter and change the code to this:

SimpleAdapter adapter = new SimpleAdapter(MainActivity.this,receiverList, R.layout.receiver_entry, new String[] { "receiverId","receiverName", "fullPath"}, new int[] {R.id.receiverId, R.id.receiverName, R.id.fullPath}) {
    @Override
    public View getView (int position, View convertView, ViewGroup parent) {
        View view = super.getView(position, convertView, parent);
        TextView receiverIdTextView = (TextView) view.findViewById(R.id.receiverId);
        if(receiverIdTextView.getText().toString().equals(String.valueOf(selectionId))) {
            view.setBackgroundColor(Color.RED);
        } else {
            view.setBackgroundColor(Color.WHITE);
        }
        return view;
    }
};

Every time one of the rows is drawn, since the getView() will get called, the ListView will check if the current view has the id of row you selected. If it doesn't, it'll change the background color to white. If it does, it'll change the background color to red.

And voila! That's it! Now you are setting the background color to red when you click on an item in the ListView.

Final Code

MainActivity.java:

public class MainActivity extends ListActivity {
    DBTools dbTools = new DBTools(this);

    ArrayList<HashMap<String, String>> receiverList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getActionBar().hide();
        setContentView(R.layout.activity_main);

        receiverList = dbTools.getAllReceivers();
        dbTools.close();
        ListView listView = getListView();
        if(receiverList.size() != 0) {
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int index, long id) {
                    view.setBackgroundColor(Color.RED);
                    TextView receiverIdTextView = (TextView) view.findViewById(R.id.receiverId);
                    selectionId = Integer.valueOf(receiverIdTextView.getText().toString());
                    ((SimpleAdapter) getListAdapter()).notifyDataSetChanged();
                 }

            });

            SimpleAdapter adapter = new SimpleAdapter(MainActivity.this,receiverList, R.layout.receiver_entry, new String[] { "receiverId","receiverName", "fullPath"}, new int[] {R.id.receiverId, R.id.receiverName, R.id.fullPath}) {
                @Override
                public View getView (int position, View convertView, ViewGroup parent) {
                    View view = super.getView(position, convertView, parent);
                    TextView receiverIdTextView = (TextView) view.findViewById(R.id.receiverId);
                    if(receiverIdTextView.getText().toString().equals(String.valueOf(selectionId))) {
                        view.setBackgroundColor(Color.RED);
                    } else {
                        view.setBackgroundColor(Color.WHITE);
                    }
                    return view;
                }
            };
            setListAdapter(adapter);
        }
    }
}

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TableRow
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/black" >

        <TextView
            android:id="@+id/titleTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:text="My List" />

    </TableRow>

        <ListView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@android:color/black"
            android:id="@android:id/list" />
</TableLayout>

receiver_entry.xml

<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/tableRow" >

    <TextView
        android:id="@+id/receiverId"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:visibility="gone" />

    <TextView
        android:id="@+id/receiverName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Robotronics" />

    <TextView
        android:id="@+id/fullPath"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="123.45.678.910:8088/robtrox/find" />

</TableRow>

这篇关于点击时创建与ListView的行选择行/换背景颜色的ListView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆