我得到JSON
{
"id_servicio": "1",
"id_motoboy": "1",
"nombre": "Juan Alexander",
"apellido": "Osorio Obreque",
"rut": "1111111",
"direccion": "Luis uribe 3690",
"telefono1": "1223214",
"comentario": "lorem ipsum",
"referencia": "Al lado del negocio Don Goyito",
"id_estado": "3",
"fecha_hora": "2015-01-13 19:51:27",
"created_at": "2015-01-13 17:51:27",
"updated_at": "-0001-11-30 00:00:00",
"productos": [
{
"id_producto": "1",
"id_empresa": "1",
"nombre": "Cuenta Rut",
"descripcion": "Mayor de 18 años",
"estado": "1",
"created_at": "2015-01-13 13:04:00",
"updated_at": "-0001-11-30 00:00:00",
"pivot": {
"id_servicio": "1",
"id_producto": "1"
}
},
{
"id_producto": "2",
"id_empresa": "1",
"nombre": "Chilena",
"descripcion": "Sueldo mayor a 300.000.-",
"estado": "1",
"created_at": "2015-01-14 13:59:31",
"updated_at": "-0001-11-30 00:00:00",
"pivot": {
"id_servicio": "1",
"id_producto": "2"
}
}
]
}
所以我在android中创建了一个带有productos
JSONArray jsonArray = new JSONArray(tmp.getString("productos"));
Button bt[] = new Button[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i ++){
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
bt[i] = new Button(DetalleServicioActivity.this);
bt[i].setText(jsonArray.getJSONObject(i).getString("nombre"));
bt[i].setTextColor(Color.parseColor("#ffffff"));
bt[i].setBackgroundColor(Color.parseColor("#17498D"));
bt[i].setLayoutParams(params);
bt[i].setEnabled(false);
bt[i].setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
rl.addView(bt[i]);
}
我需要的是保存按钮中产品的标识符(id_producto
),以便知道用户按下(选择)按钮。
我该怎么做?
答案 0 :(得分:1)
您可以将Button扩展为新类。
public Class CustomButton extends Button {
// Write your own methods & logic here
}
答案 1 :(得分:0)
使用btn.setTag(productId)
然后String productId = (String)btn.getTag()
答案 2 :(得分:0)
您可以在按钮标签(按钮[i] .setTag(id)...)和onClick(查看v)中添加ID ..您可以通过执行标记来验证哪一个被点击((按钮) )).getTag()//将返回
之前传递的id答案 3 :(得分:0)
你可以通过至少两种方式做到这一点:
1个标签(这是一个可以存储自定义数据的字段)
bt[i].setTag(jsonArray.getJSONObject(i).getString("id_producto"));
2 Closure(只是将数据传递给侦听器)
bt[i].setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String productId = jsonArray.getJSONObject(i).getString("id_producto");
}
});