我有一个显示服务器状态的程序(无论是在线还是离线)。我放了一个微调器来向用户展示它的加载,并且在 AsyncTask 中我关闭了在线/离线图像并在加载时打开微调器,完成后执行相反的操作。该代码完成了它的工作,但我觉得它是由一些小故障完成的,并且可能会在以后破坏它,所以我想现在修复它。基本上发生的是在线/离线图像的变量和微调器交换值的变量,但我不知道为什么。
这是我的代码:
public View background;
public View status;
public View loading;
class CheckStatusTask extends AsyncTask<Void, Void, Boolean> {
//show loading
protected void onPreExecute(){
status.setVisibility(View.VISIBLE);<-- this shows the spinner but should show online/offline
//loading.setVisibility(View.INVISIBLE);<-- this shows the online/offline but should show the spinner
}
//check if server is online
protected Boolean doInBackground(Void... params) {
return CheckStatus.check();
}
//set status bar to offline if flag is false
protected void onPostExecute(Boolean flag) {
status.setVisibility(View.INVISIBLE);<-- this shows the spinner but should show online/offline
//loading.setVisibility(View.VISIBLE);<-- this shows the online/offline but should show the spinner
if(!flag){
background.setBackgroundResource(R.layout.offline);
status.setBackgroundResource(R.drawable.offline);<-- correct
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
background = findViewById(R.id.status);
status = findViewById(R.id.image);
loading = findViewById(R.id.loading);
new CheckStatusTask().execute();
}
XML 文件:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" android:background="#ffffff">
<!-- Status Starts-->
<LinearLayout android:id="@+id/status"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@layout/online"
android:paddingTop="5dip"
android:paddingBottom="5dip">
<!-- Online/Offline Start-->
<ImageView android:id="@+id/image"
android:src="@drawable/logo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dip"/>
<ProgressBar
android:id="@+id/loading"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<!-- Online/Offline Ends -->
</LinearLayout>
<!-- Status Ends -->
<!-- Main Form -->
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dip"
android:layout_below="@id/status">
<TextView
android:id="@+id/text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#372c24"
android:text="Home"/>
</LinearLayout>
<!-- Main Form Ends -->
</RelativeLayout>
</ScrollView>
正如您所看到的,状态变量被定义为显示在线/离线图像,加载变量被定义为显示微调器,但它的作用恰恰相反。这只发生在此特定功能的其他任何地方。