2011-11-09 34 views
0

是否可以在Android中将一个onclicklistener添加到一个表格中?如何添加一个onclicklistener到一个tablerow?

我正在动态添加这些行,并希望能够在用户点击不同的行时打开新的屏幕。

这是我的代码添加一行。

TableRow tr = new TableRow(this); 
TableLayout.LayoutParams tableRowParams= new TableLayout.LayoutParams(TableLayout.LayoutParams.FILL_PARENT,TableLayout.LayoutParams.WRAP_CONTENT); 
int leftMargin=20; 
int topMargin=10; 
int rightMargin=15; 
int bottomMargin=20; 
tableRowParams.setMargins(leftMargin, topMargin, rightMargin, bottomMargin); 
tr.setLayoutParams(tableRowParams); 
TextView tmake=new TextView(this); 
tmake.setText(Html.fromHtml("<H1>" + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + NewText + "</H1>" + "<br />")); 
tr.addView(tmake); 
View v = new View(this); 
v.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, 1)); 
v.setBackgroundColor(Color.rgb(51, 51, 51)); 
tl.addView(v); 

回答

7

像这样;-)

tableRow.setClickable(true); 
tableRow.setOnClickListener(onClickListener); 
+0

那是伟大的,谢谢。我如何获得被点击的行的ID? onClickListener中的 – user813813

+1

是发件人视图。所以只有view.getId() – Alone89

1
/************ if table row is dynamic then this method else method 2 is perfect************/ 
//if we want to applay listener on dynamic tablerow then use this 
//sure that perfect 
TablRowe tr = new TableRow(this); 
tr.setClickable(true); 
tr.setId(100);// if in loop then add 1 counter with 100 like (100+counter) at end count++ it 
tr.setOnClickListener(this); 
@Override 
    public void onClick(View v) 
{ 
     switch (v.getId()) 
     { 
     case 100: 
       Toast.makeText(getApplicationContext(), "100", Toast.LENGTH_SHORT).show(); 
      break; 

     case 101: 
      Toast.makeText(getApplicationContext(), "101", Toast.LENGTH_SHORT).show(); 
      break; 
} 
/************************** for simple like this ************************/ 
    TableRow row1 = (TableRow)findViewById(R.id.row1); 
row1.setonClickListener(this); 
public void onClick(View v) 
{ 
switch (v.getId()) 
     { 
     case R.id.row1: 
      // do work 
      break; 
      }   
} 
相关问题