简体   繁体   中英

Change background color of listview to another color

I am working on an Application in Android where I shut down all of my servers. Therefore, I use an ArrayAdapter and a Listview.

In a background process, I iterate over the IP - Addresses and shutdown all of my servers.

Now, I want when iterating over my servers to color each row in the ListView in Green ( means still working on it to shut it down ) or Red as soon as the server is shut down.

I am able to color each row in a different color when extending the ArrayAdapter and then in the getView method coloring them all differently.

But how can I do that when iterating over each row during the background process?

My adapter is being set during the call of my Activity class.

Do I have to put the setAdapter method in my backgroundprocess, too, or something like that?

Here is my code:

protected void onCreate(Bundle savedInstanceState) {
    initComponents();
}
private void initComponents() {
    model = new SharedPreferenceModel(getBaseContext());
    mydb = new DatabaseHelper(this);
    array_list = mydb.getAllCotacts();
    hostsOnline = new ArrayList<String>();

    btnShutdown = findViewById(R.id.btnShutdown);
    lv = (ListView) findViewById(R.id.listView);
    CustomArrayAdapter custom = new CustomArrayAdapter(this, android.R.layout.simple_list_item_1, array_list);
    lv.setAdapter(custom);
}

private void addListeners(final ShutdownServers shutdownServers) {
    btnShutdown.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        new AsyncTask<Integer, String, Void>() {
            @Override
            protected Void doInBackground(Integer... params) {
                try {
                    for(int i = 0; i<array_list.size(); i++){
                        posInArray++;
                        String host = array_list.get(i);
                        if(host.equals("192.168.1.1"))
                            publishProgress("Shutdown " + host);
                        else
                            executeRemoteCommand(getBaseContext(), host);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }
            protected void onProgressUpdate(String... values) {
                hostsOnline.add(values[0]);
                custom.setNotifyOnChange(true);
                custom.notifyDataSetChanged();
            }
        }.execute(1);
        }
    });
}

Thanks for your help!

You can use setNotifyOnChange(boolean) method and corresponding add(), remove etc. methods to control list state (adding, removing, changing items). Keep in mind, that changing state of backing array field won't trigger UI changes automatically without that. If you want to control changes manually, you can use notifyDataSetChanged() method of ArrayAdapter.

It's all because ArrayAdapter tries to instantiate views only once and reuse them for different array elements when scrolling down. View's state should be only modified in getView() which normally would be called only once per array element, when it's about to be rendered on screen first time. However, you can force 'redraw' using notifyDataSetChanged() at any time to keep UI state consistent with backing array field.

lv.setBackgroundResource(R.drawable.your file)// from drawable
lv.setBackgroundResource(Color.BLACK)// from color by default

Now I was able to solve the colouring problem. Here is my solution:

public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    // Get the current item from ListView
    View view = super.getView(position,convertView,parent);

    if(notifyCalling==1 && position == getPos()){
        Log.d("getView - if - position", String.valueOf(position));
        view.setBackgroundColor(Color.GREEN);
    }else if(notifyCalling ==1 && position < getPos()){
        Log.d("getView - elseif - position", String.valueOf(position));
        view.setBackgroundColor(Color.RED);
    }else if (position % 2 == 1) {
            view.setBackgroundColor(Color.LTGRAY);
        } else {
            view.setBackgroundColor(Color.WHITE);
        }
    return view;
}

private void addListeners(final ShutdownServers shutdownServers) {
    btnShutdown.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            btnShutdown.setClickable(false);
        new AsyncTask<Integer, String, Void>() {
            @Override
            protected Void doInBackground(Integer... params) {
                try {
                    for(int i = 0; i<array_list.size(); i++){
                        String host = array_list.get(i);
                        publishProgress(host);
                        executeRemoteCommand(getBaseContext(), host);
                        setIndex(i+1);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }
            protected void onProgressUpdate(String... values) {
                custom.setNotifyOnChange(true);
                custom.notifyDataSetChanged(getIndex());
            }
        }.execute(1);
        }
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM