後this線程設置的知名度,我試着與該代碼的變量狀態欄:安卓:從的AsyncTask
private int[] loadingElementIDs;
private void initLoadingBar() {
final DisplayMetrics displayMetrics=getResources().getDisplayMetrics();
final float screenWidthInDp = displayMetrics.widthPixels/displayMetrics.density;
final int elementAmount = (int) (Math.floor(screenWidthInDp * 0.5f/30) * 5);
//set margins
LinearLayout container = (LinearLayout)findViewById(R.id.loading_outer);
...
container.requestLayout();
//declare length
loadingElementIDs = new int[elementAmount];
LayoutParams LLParams = new LayoutParams(0, LayoutParams.MATCH_PARENT);
LLParams.weight = 1f;
LinearLayout element;
for (int i=0; i<elementAmount; i++) {
int id = generateViewId(); //creates unique id
element = new LinearLayout(this);
element.setVisibility(View.INVISIBLE);
element.setLayoutParams(LLParams);
element.setBackgroundDrawable(getResources().getDrawable(R.drawable.loading_inner));
element.setId(id);
element.requestLayout();
container.addView(element);
loadingElementIDs[i] = id;
}
}
,這是對我工作的罰款,但現在我想計算某物的的AsyncTask和使元素可見(我的活動類中的代碼):
private class PrefetchData extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@SuppressWarnings("static-access")
@Override
protected Void doInBackground(Void... arg0) {
try {
int step = 0;
float totalSteps = 100f;
while (...) {
step++;
// ...................
//show status
setLoadingStatus(step/totalSteps);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Intent i = new Intent(SplashScreen.this, MainActivity.class);
startActivity(i);
finish();
}
}
public void setLoadingStatus(float percentage) {
int max = (int) Math.min(Math.floor(percentage * loadingElementIDs.length),
for (int d=0; d<max; d++) {
((LinearLayout)findViewById(loadingElementIDs[d])).setVisibility(View.VISIBLE);
LinearLayout el = (LinearLayout)this.findViewById(loadingElementIDs[d]);
el.setVisibility(LinearLayout.VISIBLE);
}
}
而這不起作用。如果我從onCreate調用setLoadingStatus(20f);
它完美,但不是在AsyncTask中。當然,我確實在活動onCreate()中開始initLoadingBar();
和new PrefetchData().execute();
。
你知道我在做什麼錯嗎?
無法從doInBackground()調用UI功能,它是一個單獨的線程(即AsnycTasks的整個目的)。你需要做onProgressUpdate()或onPostExecute() – zgc7009 2014-10-01 21:29:38