OnClickListener动态表格布局 [英] OnClickListener on dynamic table layout

查看:91
本文介绍了OnClickListener动态表格布局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

欲onClicklistener添加到从动态表中的项目时生成。 我的code是

I want to add onClicklistener to the items from the dynamic table that is generated. My Code is

for(int k=0;k<i;k++)        
{

    tr[k]=new TableRow(getApplicationContext());
    tr[k].layout(0, 0, 0, 0);
        ids[k] = new TextView(getApplicationContext());
        ids[k].setText(loc_id[k]);
        ids[k].setPadding(30, 15, 30, 15);
        loc[k] = new TextView(getApplicationContext());
        loc[k].setText(loc_name[k]);      
        loc[k].setPadding(30, 15, 30    ,15);
        tr[k].setPadding(0, 1, 0, 0);   
        tr[k].addView(ids[k]);
        tr[k].addView(loc[k]);
      tl.addView(tr[k], new TableLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

}

请帮忙。

推荐答案

您需要添加的 OnClickListner接口以您的活动,然后添加所有动态视图为 setOnClickListner 最后你可以捕捉点击事件里面的的onClick(视图查看)方式的所有观点。

You need to add OnClickListner Interface to your activity and then add all dynamic view to setOnClickListner and finally you can catch click event for all view inside onClick(View view) method.

试试这个

public class MainScreen extends Activity implements OnClickListener {

int i = 10; // input no of row

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);  // set here your layout xml name 

    //TableLayout tl = new TableLayout(MainScreen.this);
        TableLayout tl = (TableLayout) findViewById(R.id.table);
    for (int k = 0; k < i; k++) {

        TableRow tr = new TableRow(MainScreen.this);
        tr.layout(0, 0, 0, 0);
        TextView ids = new TextView(MainScreen.this);
        ids.setText(loc_id[k]);
        ids.setPadding(30, 15, 30, 15);
        TextView loc = new TextView(MainScreen.this);
        loc.setText(loc_name[k]);
        loc.setPadding(30, 15, 30, 15);
        tr.setPadding(0, 1, 0, 0);
        tr.addView(ids);
        tr.addView(loc);
        tr.setId(k); // here you can set unique id to TableRow for
                        // identification
        tr.setOnClickListener(MainScreen.this); // set TableRow onClickListner
        tl.addView(tr, new TableLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

    }

    //setContentView(tl);
}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub

    int clicked_id = v.getId(); // here you get id for clicked TableRow

    // now you can get value like this

    String ids = loc_id[clicked_id];
    String loc = loc_name[clicked_id];

}
}

这篇关于OnClickListener动态表格布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆