我正在按钮下方动态创建一些按钮和一些相应的文本视图(按钮、文本视图、按钮、文本视图......)我希望文本视图在我按下它上面的按钮时显示,并在我按下同一个按钮时再次隐藏。我为按钮和匹配的文本视图提供了相同的标签。我希望它像这样工作:用 tag1 按下按钮,用 tag1 显示 textview,再次按下按钮,它会隐藏它。现在它只在我按下任何按钮时显示和隐藏最后创建的文本视图。更新代码:
private class ReadJSONFeedTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... urls) {
return readJSONFeed(urls[0]);
}
protected void onPostExecute(String result) {
Button button1;
TextView tv;
try {
JSONArray jsonArray = new JSONArray(result);
Log.i("JSON", "Number of surveys in feed: " +
jsonArray.length());
LinearLayout news = (LinearLayout)findViewById(id.hello);
//---print out the content of the json feed---
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
button1 = new Button(getApplicationContext());
button1.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
button1.setId(i);
tv = new TextView(getApplicationContext());
tv.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
tv.setId(i);
button1.setText(jsonObject.getString("title"));
tv.setText(jsonObject.getString("text"));
news.addView(button1);
news.addView(tv);
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
v.isPressed();
if(v.getVisibility() == View.GONE) {
v.setVisibility(View.VISIBLE);
} else {
v.setVisibility(View.GONE);
}
}
});
Toast.makeText(getBaseContext(), jsonObject.getString("title") +
" - " + jsonObject.getString("text"),
Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
现在的问题是,我如何在 onClick 方法中调用变量 tv 。它不会让我向参数添加另一个视图,而 i View v 是按钮的视图。我该如何解决?