Htetwai YanSoe
Htetwai YanSoe

Reputation: 37

ListView. Is there a way to change the colour of rows in Listview in android according to variable?

My code is as follows: This allows me to show data from the database(mySQL) but what i want to do is to change the color rows according to the variable called trolley count and this is what i coded. Shows a normal listview with same color background. Is it possible to change it according to what I want? NO clicking is to be involved. Activity UI. I want it to display like this whereby trolley count less than 5 will be red, trolley count more than 5 but less than 15 to display orange, trolley count more than 15 to display green

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer);
    mToggle = new ActionBarDrawerToggle(this,mDrawerLayout,R.string.open,R.string.close);
    mDrawerLayout.addDrawerListener(mToggle);
    mToggle.syncState();
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    NavigationView navigationView = (NavigationView)findViewById(R.id.navigation_view);
    navigationView.setNavigationItemSelectedListener(this);

    listView = (ListView)findViewById(R.id.listView);
    adapter = new ArrayAdapter<String> (this,android.R.layout.simple_list_item_1);
    listView.setAdapter(adapter);
    new Connection().execute();

    btn =(Button) findViewById(R.id.button2);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            openActivity2();
        }
    });
}

private void openActivity2() {
    Intent in = new Intent(this,Main2Activity.class);
    startActivity(in);
}

@Override
public void onPointerCaptureChanged(boolean hasCapture) {

}

class Connection extends AsyncTask<String, String, String>{

    @Override
    protected String doInBackground(String... strings) {
        String result = "";
        String host = "http://10.0.3.2/Client/docks.php";
        try
        {
            HttpClient client = new DefaultHttpClient();
            HttpGet request = new HttpGet();
            request.setURI(new URI(host));
            HttpResponse response = client.execute(request);
            BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            StringBuffer stringBuffer = new StringBuffer("");

            String line = "";
            while ((line = reader.readLine())!=null)
            {
                stringBuffer.append(line);
                break;
            }
            reader.close();
            result = stringBuffer.toString();


        }
        catch(Exception e)
        {
            return new String("There exception: "+e.getMessage());
        }

        return result;
    }
    @Override
    protected void onPostExecute(String result)
    {
        Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show();
        try {
            JSONObject jsonResult = new JSONObject(result);
            int success = jsonResult.getInt("success");
            if(success==1)
            {
                JSONArray data = jsonResult.getJSONArray("abc");
                for(int i = 0; i < data.length(); i++)
                {
                    JSONObject data1 = data.getJSONObject(i);
                    int id = data1.getInt("dock_id");
                    String name = data1.getString("dock_name");
                    String description = data1.getString("dock_desc");
                    int flightarrival = data1.getInt("flight_arrival");
                    int count = data1.getInt("trolley_count");
                    String time = data1.getString("snapshot_time");
                    String line = id+"."+name+"-"+count+"-"+flightarrival+"-"+time;
                    adapter.add(line);






                }
            }
            else
            {
                Toast.makeText(getApplicationContext(), "there is no data", Toast.LENGTH_SHORT).show();
            }
        } catch (JSONException e) {
            Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
        }

    }
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
    if(mToggle.onOptionsItemSelected(item))
    {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    int id = item.getItemId();
    if( id == R.id.home)
    {
        Toast.makeText(this,"This is home", Toast.LENGTH_SHORT).show();
    }
    if( id == R.id.trolleycount)
    {
        Toast.makeText(this,"This is trolleycount", Toast.LENGTH_SHORT).show();
    }
    if( id == R.id.log)
    {
        Intent in = new Intent(this,MainActivity.class);
        startActivity(in);
        Toast.makeText(this,"You have successfully logged out of your account", Toast.LENGTH_SHORT).show();

    }
    return false;
    }
}

Upvotes: 3

Views: 273

Answers (4)

Ali Ahmed
Ali Ahmed

Reputation: 2178

You can use below code to change background color of each row.

In your onPost method like this

    //Above code remains same,,

    String line = id+"."+name+"-"+count+"-"+flightarrival+"-"+time;
    adapter.add(line);

    int items_count = listView.getAdapter().getCount();
    int i = 0;
    while (i <= items_count) {
        if (i < 5) {
            listView.getChildAt(i).setBackgroundColor(getResources().getColor(android.R.color.holo_red_dark));
        } else if (i >= 5 || i < 15) {
            listView.getChildAt(i).setBackgroundColor(getResources().getColor(android.R.color.holo_orange_dark));
        } else {
            listView.getChildAt(i).setBackgroundColor(getResources().getColor(android.R.color.holo_green_dark));
        }
        ++i;
    }

Upvotes: 2

hossam scott
hossam scott

Reputation: 466

You can change the background color with this code :

    String color = "#eff0f1";
    Drawable mDrawable = context.getResources().getDrawable(R.drawable.circle_background_inside).mutate();
    mDrawable.setColorFilter(new
            PorterDuffColorFilter(Color.parseColor(color), PorterDuff.Mode.SRC_IN));
    binding.layoutColor.setBackground(mDrawable);

Upvotes: 0

Namini40
Namini40

Reputation: 140

the idea is using a custome list view items

CostomItems adapter = new CustomItems(context,list);


private class CutomItems extends ArrayAdapter<String> {
    public CutomItems(@NonNull Context context, ArrayList<String> list) {
        super(context, R.layout.cutom_items, list);
    }


    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        LayoutInflater layoutInflater = LayoutInflater.from(getContext());
        View myView = layoutInflater.inflate(R.layout.cutom_items, parent, false);

        TextView textOfItems = myView.findViewById(R.id.textOfItems);

        if (some condition){
        textOfItems.setBackgroundColor(R.color.red);
        }else if (some other condition){
        textOfItems.setBackgroundColor(R.color.blue);
        }

        return myView;
    }
}

as you can see I created a class extending ArrayAdapter which is using Items from a layout called cutome_items. lets say that my custom items is only a text view. when ever that getView Function gets called (when listview created) each item's color will be different depending on the conditions or what ever you want!

Upvotes: 1

Bilal Naeem
Bilal Naeem

Reputation: 1087

A way to do this will be to use a custom adapter and override the getItemViewType(int position) method. Doing that you can select the view based on any parameter or variable

Example

public class CustomAdapter extends ListView.Adapter<ViewHolder> {
    @Override
    public int getItemViewType(int position) {
    //Here you can return an integer based on some value
    return (itemCount < 5 ? 0 : (itemCount > 15 ? 1 : 2));
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
     switch (viewType) {
         case 0: return new ViewHolder0(...);
         case 1: return new ViewHolder2(...);
         ...
     }
}

You can simply create custom viewholders with different background color.

You can look into this answer: How to create RecyclerView with multiple view type?

Upvotes: 1

Related Questions