我需要在每个动态生成的textview上添加一个click事件。
textview采用数组形式,我添加了从json字符串中提取的文本视图。
指导我如何实现它。
下面是我的代码:
Button b =(Button) findViewById(R.id.start);
b.setOnClickListener(this);
starters = (TextView) findViewById(R.id.textView1);
starters.setOnClickListener(this);
tl = (TableLayout) findViewById(R.id.tablelayout1);
rl = (RelativeLayout) findViewById(R.id.rel1);
itemList = new ArrayList<HashMap<String, String>>();
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_Name, name);
startActivity(in);
}
});
new Getitems().execute();
}
@Override
public void onClick(View arg0) {
switch(arg0.getId()){
case R.id.textView1:
ontextview1click();
break;
case R.id.start:
try {
onbuttonclick();
} catch (JSONException e) {
e.printStackTrace();
}
break;
}
}
private void onbuttonclick() throws JSONException {
TableRow[] tr = new TableRow[items.length()];
TextView[] tx = new TextView[items.length()];
TableLayout tl = (TableLayout) findViewById(R.id.tablelayout1);
for (int i = 0; i < items.length(); i++) {
JSONObject c = items.getJSONObject(i);
String category = c.getString(TAG_Cat);
tx[i] = new TextView(S1.this);
tx[i].setLayoutParams(new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
tx[i].setText(category);
tr[i] = new TableRow(S1.this);
tr[i].setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
tr[i].addView(tx[i],new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
tl.addView(tr[i],new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
}
}
private void ontextview1click() {
if (key==0){
key=1;
lv.setVisibility(View.VISIBLE);
}
else if(key==1) {
key=0;
lv.setVisibility(View.GONE);
}
}
答案 0 :(得分:0)
tx[i].setOnClickListener(this);
然后点击方法
public void onClick(View arg0) {
if(arg0==tx[i]){
}
}