我有一个下载服务,可以通过回调更新 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:我想我应该提到项目是 aViewPager
中的不同片段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 元素都已正确设置。仅当我进行实时更改时才会发生这种情况。
谢谢。