setTextColor使用颜色值可编程

时间:2018-09-18 06:31:02

标签: android android-layout android-xml

我需要在适配器类上而不是在活动中设置文本颜色,并使用在colors.xml文件中记录的颜色值!

这是代码:如有遗漏,敬请原谅 这是代码:对任何遗漏的东西表示抱歉 这是代码:抱歉,缺少任何东西

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.myViewHolder> {
private final LayoutInflater inflater;
ArrayList<HashMap<String, String>> productsHashMapList;

/*int[] images = {
        R.drawable.ic_launcher_foreground,
        R.drawable.ic_launcher_background,
        R.drawable.ic_launcher_foreground
};*/

public MyAdapter(Context context, ArrayList<HashMap<String, String>> productsJsonList){
    inflater = LayoutInflater.from(context);
    this.productsHashMapList = productsJsonList;

}

@Override
public myViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    View view = inflater.inflate(R.layout.list_row,parent,false);
    myViewHolder holder = new myViewHolder(view);

    return holder;
}

@Override
public void onBindViewHolder(myViewHolder holder, int position) {
    holder._productName.setText(productsHashMapList.get(position).get("name"));
    holder._productName.setTextColor(getResources().getColor(R.color.colorRed));

}

@Override
public int getItemCount() {
    return productsHashMapList.size();
}

public class myViewHolder extends RecyclerView.ViewHolder {

    ImageView   _imgview;
    TextView    _productName;


    public myViewHolder(View itemView) {

        super(itemView);
        _imgview            = (ImageView) itemView.findViewById(R.id.logo);
        _productName           = (TextView) itemView.findViewById(R.id.productName);
    }
}

}

4 个答案:

答案 0 :(得分:2)

首先在Activity中初始化适配器并在适配器中设置上下文的同时,从Activity通过适配器的构造函数传递上下文:

this.context = context; // set this in the constructor.

然后,设置textColor:

textView.setTextColor(context.getResources().getColor(R.color.white)); //whatever your color

答案 1 :(得分:0)

尝试

textViewOBJ.setTextColor(ContextCompat.getColor(context, R.color.your_color_code));

仅供参考

您应该通过Context

如何?

通过您的适配器类。 # Constructor

 ArrayList<HashMap<String, String>> productsHashMapList;
   Context context;

public MyAdapter(Context contextOBJ, ArrayList<HashMap<String, String>> productsJsonList){
    this.context=contextOBJ;
    inflater = LayoutInflater.from(context);
    this.productsHashMapList = productsJsonList;

}

答案 2 :(得分:0)

textView.setTextColor(getResources().getColor(R.color.color));

根据prashanth verma anser,

将constructor中的上下文具体化。 然后在代码中使用它。

textView.setTextColor(context.getResources().getColor(R.color.color));

答案 3 :(得分:0)

始终在RecyclerView.ViewHolder类内部而不是在适配器类的onBindViewHolder方法内部设置文本颜色,请查看以下解决方案

class MyViewHolder extends RecyclerView.ViewHolder {
 private TextView YOUR_TEXT_VIEW;
        MyViewHolder(View view) {
            super(view);
        YOUR_TEXT_VIEW = view.findViewById(R.id.YOUR_TEXT_VIEW);

        YOUR_TEXT_VIEW.setTextColor(ContextCompat.getColor(YOUR_APP_CONTEXT, R.color.your_color_code));

        }


    }