我有一个下载服务,通过回调更新UI。例如,如果我取消下载任务,则正确项目的UI应相应更改。 UI更新方法如下所示:
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
downloadSwitch.setClickable(true);
downloadSwitch.setChecked(false);
downloadSwitchText.setText(R.string.switch_download_available);
downloadSwitchText.setVisibility(View.VISIBLE);
downloadSwitch.setDownloadState(State.READY);
}
});
我注意到,有时在调用此方法后,只有文本更改,但交换机保持选中状态,反之亦然。有人遇到过这个问题吗?
EDIT_1:我想我应该提一下,ViewPager
Activity
中的项目是不同的片段,这些方法位于片段中
EDIT_2:自定义切换
public class DownloadSwitch extends Switch {
private static final String TAG = DownloadSwitch.class.getSimpleName();
private State downloadState;
public DownloadSwitch(Context context) {
super(context);
}
public DownloadSwitch(Context context, AttributeSet attrs) {
super(context, attrs);
initCostumeAttrs(attrs);
}
public DownloadSwitch(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initCostumeAttrs(attrs);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public DownloadSwitch(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
initCostumeAttrs(attrs);
}
private void initCostumeAttrs(AttributeSet attributeSet){
TypedArray attributes = getContext().getTheme().obtainStyledAttributes(attributeSet, R.styleable.DownloadSwitch, 0, 0);
int intState = attributes.getInt(R.styleable.DownloadSwitch_state, 0);
switch (intState){
case 0:
downloadState = State.READY;
setChecked(false);
break;
case 1:
downloadState = State.DOWNLOADING;
setChecked(true);
break;
case 2:
downloadState = State.DONE;
setChecked(true);
break;
}
attributes.recycle();
}
@Override
public void setClickable(boolean clickable) {
super.setClickable(clickable);
if(clickable){
setVisibility(VISIBLE);
} else {
setVisibility(GONE);
}
}
@Override
public void setChecked(boolean checked) {
super.setChecked(checked);
changeColor(checked);
}
private void changeColor(boolean checked) {
int thumbColor;
int trackColor;
if(checked){
thumbColor = Color.argb(225, 226, 6, 19);
trackColor = Color.argb(225, 0, 244, 217);
} else {
thumbColor = Color.argb(225, 255, 255, 255);
trackColor = Color.argb(225, 221, 221, 221);
}
try {
getThumbDrawable().setColorFilter(thumbColor, PorterDuff.Mode.MULTIPLY);
getTrackDrawable().setColorFilter(trackColor, PorterDuff.Mode.MULTIPLY);
}
catch (NullPointerException e) {
e.printStackTrace();
}
}
我注意到NullPointerException
有时会changeColor()
。也许它与此有关?加载活动时,所有UI元素都已正确设置。只有在我进行实时更改时才会发生这种情况。
感谢。