0

I want to ask you, how to change programmatically the background color of LinearLayout in CardView when the text in TextView equals specify word or is empty. For example field1 getting string "red", the background of LinearLayout gets red. I'm fetching the data from JSON php file.

MainActivity.class

public class MainActivity extends AppCompatActivity {

    private String jsonURL = "http://example.com/test.php";
    private final int jsoncode = 1;
    private RecyclerView recyclerView;
    ArrayList<Model> ModelArrayList;
    private Adapter adapter;
    private static ProgressDialog mProgressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView = findViewById(R.id.recycler);
        fetchJSON();

    }
    @SuppressLint("StaticFieldLeak")
    private void fetchJSON(){

        new AsyncTask<Void, Void, String>(){
            protected String doInBackground(Void[] params) {
                String response="";
                HashMap<String, String> map=new HashMap<>();
                try {
                    HttpRequest req = new HttpRequest(jsonURL);
                    response = req.prepare(HttpRequest.Method.POST).withData(map).sendAndReadString();
                } catch (Exception e) {
                    response=e.getMessage();
                }
                return response;
            }
            protected void onPostExecute(String result) {
                //do something with response
                onTaskCompleted(result,jsoncode);
            }
        }.execute();
    }

    public void onTaskCompleted(String response, int serviceCode) {
        Log.d("responsejson", response.toString());
        switch (serviceCode) {
            case jsoncode:
                if (isSuccess(response)) {
                    removeSimpleProgressDialog();  //will remove progress dialog
                    ModelArrayList = getInfo(response);
                    adapter = new Adapter(this,ModelArrayList);
                    recyclerView.setAdapter(adapter);
                    recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false));

                }else {
                    Toast.makeText(MainActivity.this, getErrorCode(response), Toast.LENGTH_SHORT).show();
                }
        }
    }

    public ArrayList<Model> getInfo(String response) {
        ArrayList<Model> ModelArrayList = new ArrayList<>();
        try {
            JSONObject jsonObject = new JSONObject(response);
            if (jsonObject.getString("status").equals("true")) {
                JSONArray dataArray = jsonObject.getJSONArray("data");
                for (int i = 0; i < dataArray.length(); i++) {
                    Model fieldsModel = new Model();
                    JSONObject dataobj = dataArray.getJSONObject(i);
                    fieldsModel.setField1(dataobj.getString("field1"));
                    fieldsModel.setField2(dataobj.getString("field2"));
                    ModelArrayList.add(fieldsModel);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return ModelArrayList;
    }

    public boolean isSuccess(String response) {
        try {
            JSONObject jsonObject = new JSONObject(response);
            if (jsonObject.optString("status").equals("true")) {
                return true;
            } else {

                return false;
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return false;
    }

    public String getErrorCode(String response) {
        try {
            JSONObject jsonObject = new JSONObject(response);
            return jsonObject.getString("message");

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return "No data";
    }

}

Adapter.class

public class Adapter extends RecyclerView.Adapter<Adapter.MyViewHolder> {

    private LayoutInflater inflater;
    private ArrayList<Model> ModelArrayList;

    public Adapter(Context ctx, ArrayList<Model> rogerModelArrayList){
        inflater = LayoutInflater.from(ctx);
        this.ModelArrayList = rogerModelArrayList;
    }

    @Override
    public Adapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = inflater.inflate(R.layout.rv_item, parent, false);
        MyViewHolder holder = new MyViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(Adapter.MyViewHolder holder, int position) {
        holder.field1.setText(ModelArrayList.get(position).getField1());
        holder.field2.setText(ModelArrayList.get(position).getField2());
    }

    @Override
    public int getItemCount() {
        return ModelArrayList.size();
    }
    class MyViewHolder extends RecyclerView.ViewHolder{
        TextView field1,field2;

        public MyViewHolder(View itemView) {
            super(itemView);
            field1 = (TextView) itemView.findViewById(R.id.field1);
            field2 = (TextView) itemView.findViewById(R.id.field2);
        }

    }
}

Model.class

public class Model {

    private String field1, field2;

    public String getField1() {
        return field1;
    }
    public void setField1(String field1) {
        this.field1 = field1;
    }

    public String getField2() {
        return field2;
    }
    public void setField2(String field2) {
        this.field2 = field2;
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#cd15e6"
    tools:context=".MainActivity">

   ** <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:layout_marginTop="15dp"/> **


</LinearLayout>

rv_item.xml Here is the LinearLayout which i want to change the color LL_background

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.CardView
        android:id="@+id/card_view" 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        app:cardCornerRadius="5dp">

           <LinearLayout
            android:id="@+id/LL_background"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal">


            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="100dp"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="10dp"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/field1"
                    android:layout_width="wrap_content"
                    android:layout_height="0dp"
                    android:layout_marginTop="5dp"
                    android:layout_weight="1"
                    android:text="ddd"
                    android:textColor="#000"
                    android:textStyle="bold" />

                <TextView
                    android:id="@+id/field2"
                    android:layout_width="wrap_content"
                    android:layout_height="0dp"
                    android:layout_weight="1"
                    android:text="ddd"
                    android:textColor="#000"
                    android:textStyle="bold" />

            </LinearLayout>
        </LinearLayout>

    </android.support.v7.widget.CardView>

</LinearLayout>

Please check my project and share your ideas. Thanks a lot

Iliyan
  • 39
  • 6

2 Answers2

0

First of all add layout reference to ViewHolder

class MyViewHolder extends RecyclerView.ViewHolder{
    TextView field1,field2;
    LinearLayout layout;

    public MyViewHolder(View itemView) {
        super(itemView);
        field1 = (TextView) itemView.findViewById(R.id.field1);
        field2 = (TextView) itemView.findViewById(R.id.field2);
        layout = itemView.findViewById(R.id.LL_background);
    }
}

Then check Field1 and set color

@Override
public void onBindViewHolder(Adapter.MyViewHolder holder, int position) {
    holder.field1.setText(ModelArrayList.get(position).getField1());
    holder.field2.setText(ModelArrayList.get(position).getField2());

    if(ModelArrayList.get(position).getField1().equalIgnoreCase("red")
        holder.layout.setBackgroundColor(Color.RED)
}

red is not recognizable in android. Either you have to handle it manually like above or you can send the corresponding #code of color from server and handle it like below:

holder.layout.setBackgroundColor(Color.parseColor("#ff0000"));
Md. Asaduzzaman
  • 14,963
  • 2
  • 34
  • 46
0

You can change layout instead color. Create different layouts that has different background color or different design. Then do this.

@Override
public Adapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = inflater.inflate(R.layout.rv_item, parent, false);
    if(ModelArrayList.get(position).getField1().equalIgnoreCase("red")
      view = inflater.inflate(R.layout.anotherLayout, parent, false);
    MyViewHolder holder = new MyViewHolder(view);
    return holder;
}