Android SeekBar通过Java代码修改自定义progressDrawable不生效如何解决
问题原因
动态设置SeekBar的progressDrawable时,Android不会自动同步Drawable的绘制边界与原有进度状态,再加上Drawable资源默认的状态共享机制,就会出现显示异常、不生效的问题。
解决步骤
使用兼容方法获取Drawable并开启独立状态
调用mutate()避免同资源的Drawable实例状态互相影响,同时用兼容API适配不同系统版本:Drawable correctDrawable = ContextCompat.getDrawable(context, R.drawable.progress_tract_correct_option).mutate();设置Drawable后同步进度状态
先保存原有进度,设置完Drawable后重新赋值进度,触发SeekBar刷新,同时确保进度值大于0(进度为0时进度部分默认不显示):// 示例:修改option1对应的SeekBar int currentProgress = holder.seekMcqBar1.getProgress(); holder.seekMcqBar1.setProgressDrawable(correctDrawable); // 重新设置进度触发Drawable状态更新 holder.seekMcqBar1.setProgress(0); holder.seekMcqBar1.setProgress(currentProgress); // 确保进度值大于0,替换为你的实际业务进度值 if (currentProgress == 0) { holder.seekMcqBar1.setProgress(50); } holder.seekMcqBar1.invalidate();可选优化:清理自定义Drawable冗余属性
你的progress_tract_correct_option中scale标签下的android:layout_width="wrap_content"是无效属性,可以删除,避免潜在的解析异常。
完整修改后的逻辑示例
String answer = modelAskQuestionAdmin.getAnswer(); String option1 = modelAskQuestionAdmin.getOption1(); String option2 = modelAskQuestionAdmin.getOption2(); String option3 = modelAskQuestionAdmin.getOption3(); String option4 = modelAskQuestionAdmin.getOption4(); // 封装公用方法减少重复代码 private void updateSeekBarStyle(SeekBar seekBar, TextView optionTv, TextView percentTv, int optionIconRes) { int currentProgress = seekBar.getProgress(); Drawable correctDrawable = ContextCompat.getDrawable(context, R.drawable.progress_tract_correct_option).mutate(); seekBar.setProgressDrawable(correctDrawable); seekBar.setProgress(0); seekBar.setProgress(currentProgress); // 替换为实际业务的进度值,确保大于0才会显示进度 if (currentProgress == 0) { seekBar.setProgress(/* 你的实际进度值,比如投票占比数值 */); } optionTv.setCompoundDrawablesWithIntrinsicBounds(optionIconRes, 0, 0,0); percentTv.setTextColor(ContextCompat.getColor(context, R.color.colorPrimary)); seekBar.invalidate(); } if(answer.equals(option1)){ updateSeekBarStyle(holder.seekMcqBar1, holder.option1MCQTv, holder.option1PercentTv, R.drawable.ic_option1_primary_color); } else if(answer.equals(option2)){ updateSeekBarStyle(holder.seekMcqBar2, holder.option2MCQTv, holder.option2PercentTv, R.drawable.ic_option2_color_primary); } else if(answer.equals(option3)){ updateSeekBarStyle(holder.seekMcqBar3, holder.option3MCQTv, holder.option3PercentTv, R.drawable.ic_option3_color_primary); } else if(answer.equals(option4)){ updateSeekBarStyle(holder.seekMcqBar4, holder.option4MCQTv, holder.option4PercentTv, R.drawable.ic_option4_color_primary); }
内容的提问来源于stack exchange,提问作者Pawan Kumar
相关产品推荐
相关产品推荐

