Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
284 views
in Technique[技术] by (71.8m points)

android - How to change background color of each row in list view?

My app contains 1 list view, data source is 1 sqlite table, when i hold long click on any row in listview it will show me 1 menu option to change the color of that row, for this i have used onContextItemSelected function, on selecting menu option it will call 1 function change_color. What should i write in change_color function so that i can change row bg color.

    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.add(0, PROCESSED_ID, 0, R.string.menu_processed);
    }



    public boolean onContextItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case PROCESSED_ID:
            AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
                    .getMenuInfo();

            change_color();
            return true;
        }
        return super.onContextItemSelected(item);
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Call your method as :

change_color(pass_your_list_view, pass_selected_position_of_list_view);

And define change_color() as:

private void change_color(ListView listView, int position) {
    listView.getChildAt(position).setBackgroundColor(Color.BLACK);
}

Hope this will help.

Edited

Define a variable a position

public static int position;

And replace your code as

public void onCreateContextMenu(ContextMenu menu, View v,
        ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    menu.add(0, PROCESSED_ID, 0, R.string.menu_processed);

    // Get the info on which item was selected
    AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
    // Retrieve the position at where you long pressed
    position = info.position;

}



public boolean onContextItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case PROCESSED_ID:
        AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
                .getMenuInfo();

        change_color(getListView(), position);
        return true;
    }
    return super.onContextItemSelected(item);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...