以下代码当前在我的 main 的 onCreate() 中运行。我现在只是在测试。我一直试图在 AsyncTask 中完成这项工作,因为目标是以后能够动态更新这些,但似乎无法找到如何做到这一点。我想知道是否有人有一些见识。谢谢!
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 中的实例,只是为了测试和理解这一点,但我遇到了错误,我一直在对其进行操作,但似乎没有任何效果。