【发布时间】:2016-01-07 17:19:27
【问题描述】:
我在为运行时生成的按钮构建正确的 OnClicklistener 时遇到问题。我在 stackoverflow 上找到了一些线程,但经过多次尝试后,我无法正常工作。
我有一个方法可以在左侧“列”和右侧“列”x 按钮中构建一个带有 TextView 的 GUI。每个按钮都有一个其他链接,应该由 onClick 打开。在运行时创建之前我不知道该链接。
这是我的代码和我的实际尝试。但在这种情况下,我每次只得到最后生成的按钮的链接。如果我点击第一个,第二个....每次都是同一个链接。
希望有解决办法!
private void createNewView (String JsonInputBeacon, String JsonInputConfig){
TableLayout tableLayout = new TableLayout(this);
tableLayout.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT));
tableLayout.setStretchAllColumns(true);
try {
final JSONArray jsonArrayBeacon = new JSONArray(JsonInputBeacon);
final JSONArray jsonArrayConfig = new JSONArray(JsonInputConfig);
int Patientencounter = 1;
for(int JsonObjectCounterBeacon = 0; JsonObjectCounterBeacon < jsonArrayBeacon.length(); JsonObjectCounterBeacon ++ ){
final JSONObject objectBeacon = jsonArrayBeacon.getJSONObject(JsonObjectCounterBeacon);
TableRow row = new TableRow(this);
TextView outputLeft = new TextView(this);
outputLeft.setText("Patient " + Patientencounter + ":\n" + "Name: " + objectBeacon.getString("surname") + ", " + objectBeacon.getString("firstName") + "\n" + "Geb-Datum: " + objectBeacon.getString("birthdate"));
row.addView(outputLeft);
for (int JsonObjectCounterConfig = 0; JsonObjectCounterConfig < jsonArrayConfig.length(); JsonObjectCounterConfig++){
final JSONObject objectConfig = jsonArrayConfig.getJSONObject(JsonObjectCounterConfig);
TableRow rowRight = new TableRow(this);
Button buttonRight = new Button(getApplicationContext());
buttonRight.setText(objectConfig.getString("name"));
final String myURL = objectConfig.getString("link");
buttonRight.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW,Uri.parse(myURL));
startActivity(browserIntent);
}
});
rowRight.addView(buttonRight);
row.addView(rowRight);
}
tableLayout.addView(row);
Patientencounter +=1;
}
} catch (JSONException e) {
e.printStackTrace();
}
setContentView(tableLayout);
}
【问题讨论】:
标签: android json android-layout button onclicklistener