我正在尝试调用一个动态生成按钮的方法onPostExecute方法的AsyncTask.OnPostExecute结果可以像S~D~W~H~H~A这样的结果。我需要动态创建按钮
private TextView textView;
LinearLayout layout;
Button btn;
List<String> elements;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.TextView01);
layout= (LinearLayout) findViewById(R.id.layoutFor);
}
private class ExecuteTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
@Override
protected void onPostExecute(String result) {
elements = Arrays.asList(result.split("~"));
generateButtonDynamically();
}
}
public void onClick(View view) {
ExecuteTask task = new ExecuteTask ();
task.execute(new String[] {"url"});
}
public void generateButtonDynamically()
{
for (int i = 0; i < elements.size(); i++) {
LinearLayout linearLayout = (LinearLayout)findViewById(R.id.layoutFor);
Button btn = new Button(this);
btn.setText(elements.get(i));
linearLayout.addView(btn);
}
}
在generateButtonDynamically方法中。我正在尝试动态生成按钮并显示。但它没有发生。
答案 0 :(得分:3)
不需要在 onPostExecute() 方法中再次找到 LinearLayout 的ID。你已经全球宣布了。
另外一件事为按钮和检查设置 LayoutParams
for (int i = 0; i < elements.size(); i++) {
Button btn = new Button(YourActivity.this);
btn.setLayoutParams(new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
btn.setGravity(Gravity.CENTER | Gravity.RIGHT);
btn.setText(elements.get(i));
linearLayout.addView(btn);
}
答案 1 :(得分:0)
您已通过引用LinearLayout
在onCreate()
中找到了layout
。在方法generateButtonDynamically()
答案 2 :(得分:0)
我不知道你是否已经解决了。尝试更改
Button btn = new Button(this);
在
Button btn = new Button(getApplicationContext());
我认为在那一刻这个指向 ExecuteTask 类而不是需要的 Context 。 我有类似的问题,我以这种方式解决了它。