java - 如何仅更改 TextView 的背景 alpha 而不是整个视图?
问题描述
注意:这可能是重复的帖子。但是以前的解决方案对我没有用...
我正在尝试从 RecyclerView 适配器(而不是 textColor 和背景)内部设置 TextView(仅)背景不透明度。上一个问题的答案对我不起作用。
先前建议的输出
情况1:
holder.textView.setBackgroundColor(Color.argb(50, 0,255,0)); //this set alpha to whole view(both background + textColor).
案例二:
holder.textView.setAlpha(50); //this also set alpha to whole view(both background + textColor).
案例3:
holder.textView.getBackground().setAlpha(alpha); //NullPointerException
输出
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.graphics.drawable.Drawable.setAlpha(int)' on a null object reference
这是我的 RecyclerView :
...
@RequiresApi(api = Build.VERSION_CODES.O)
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
TextView textView = new TextView(parent.getContext());
return new ViewHolder(textView);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
holder.textView.setAlpha(50);
}
static class ViewHolder extends RecyclerView.ViewHolder {
private TextView textView;
@RequiresApi(api = Build.VERSION_CODES.O)
public ViewHolder(@NonNull View itemView) {
super(itemView);
this.textView = (TextView) itemView;
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
textView.setLayoutParams(layoutParams);
textView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
textView.setPadding(4,4,4,4);
textView.setAutoSizeTextTypeUniformWithConfiguration(6,24,1, TypedValue.COMPLEX_UNIT_DIP);
}
}
...
解决方案
试试这个:
....
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
ShapeDrawable drawable = new ShapeDrawable();
drawable.getPaint().setColor(Color.GREEN); //Your color;
drawable.getPaint().setAlpha(75); //BackGround Alpha between 0 to 100;
holder.textView.setBackground(drawable);
}
推荐阅读
- biztalk - 是否在 AS2 消息中加密了 MIME 标头?
- php - 如何解决 MySQLi 中的“重复条目”错误
- python - python请求无法连接到NSE india,连接错误
- python - 从 http 更改为 https 后 Python 请求没有得到响应
- sql - 使用 laravel 中的 SQL 查询将 Auth::user()-id 存储在数据库中
- php - 在我的服务器上哪里可以找到 php-fpm.log 和 php-fpm.conf?
- php - 登录后页面不重定向
- c++ - 如何让我的虚拟机使用 CNTLM 在代理后面下载 https 文件,用 Qt 用 C++ 编写?
- python - Pandas 从 ExcelWriter 创建 zip 文件
- .net - NUnit TestCase 不能引用实例成员