以编程方式更改LinearLayout的背景颜色

我想问你,当TextView中的文本等于指定单词或为空时,如何以编程方式更改CardView中LinearLayout的背景颜色。例如,field1获得字符串“ red”,则LinearLayout的背景变为红色。我正在从JSON php文件中获取数据。

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 这是我要更改颜色 LL_background

的LinearLayout
<?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>

请检查我的项目并分享您的想法。非常感谢?

my7cmy7c 回答:以编程方式更改LinearLayout的背景颜色

首先将布局引用添加到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);
    }
}

然后检查Field1并设置颜色

@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)
}

红色在android中无法识别。您要么像上面一样手动处理它,要么可以从服务器发送相应的颜色#code并像下面这样处理它:

holder.layout.setBackgroundColor(Color.parseColor("#ff0000"));
,

您可以更改布局而不是颜色。创建具有不同背景颜色或不同设计的不同布局。然后这样做。

@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,false);
    MyViewHolder holder = new MyViewHolder(view);
    return holder;
}
本文链接:https://www.f2er.com/3156939.html

大家都在问