以下代码当前在我的main的onCreate()中运行。我现在只是在测试。我一直试图在AsyncTask中完成这项工作,因为我们的目标是能够稍后动态更新这些内容,但似乎无法找到如何做到这一点。我想知道是否有人有一些见解。谢谢!使用AsyncTask更新UI(动态布局)
LinearLayout ObjectLayout = (LinearLayout) findViewById(R.id.LayoutObjects);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
params.height = 140;
params.width = 140;
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
for (int i = 0; i < 10; i++) {
Button btn = new Button(this);
btn.setLayoutParams(params);
btn.setPadding(0, 50, 0, 0);
btn.setTextSize(14);
btn.setText("MyButton");
btn.setTextColor(color.Yellow);
// Drawable image = Drawable.createFromPath("@drawable/add_page");
// //
// btn.setBackgroundDrawable(image);
btn.setBackgroundDrawable(getResources().getDrawable(
R.drawable.add_page));
// btn.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
ObjectLayout.addView(btn);
}
private class GetDataTask2 extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
// Simulates a background job.
for (int i = 0; i < 10; i++) {
publishProgress(btn2);
}
return null;
}
protected void publishProgress(Button btn2) {
btn2.setLayoutParams(params2);
btn2.setPadding(0, 50, 0, 0);
btn2.setTextSize(14);
btn2.setText("MyButton yo yo yo ");
btn2.setTextColor(color.Yellow);
btn2.setBackgroundDrawable(getResources().getDrawable(
R.drawable.add_page));
ObjectLayout2.addView(btn2);
// Process width and height
}
protected void onPostExecute() {
// Do some stuff here
// Call onRefreshComplete when the list has been refreshed.
}
}
这里这段代码是我为我的异步和定义的布局和按钮创建为实例中mainactivity,只是为了测试和理解这一点,但我得到的错误,我一直在围绕操纵它,但似乎没有上班。
”首先,您需要将Context和LinearLayout传递给AsyncTask,只需使用自定义构造函数即可。“究竟是什么样子,对于愚蠢的问题抱歉,只是有点困惑。 – thekevshow
添加到答案的链接。 – Geobits
我添加了更多的代码,关于异步我会去关于自定义构造函数后,我得到这个测试工作,并理解它好一点,只是好奇,如果你可以看看看什么是错的。 – thekevshow