簡體   English   中英

動態表布局上的OnClickListener

[英]OnClickListener on dynamic table layout

我想將onClicklistener添加到生成的動態表中的項目。 我的代碼是

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(視圖視圖)方法中的所有視圖的click事件。

試試這個

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];

}
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM