Monday, 21 November 2011

Dynamic row in TableLayout with more than one column click-able.

some time we are having problem  to make more than one column click-able in case of dynamic addition of rows in table layout, but it is pretty simple.

how? we will see here and at end you will find link for test project.

step 1: inflate table row layout using LayoutInflater and find the columns where you want to add click action, tag that columns view with "unique" value.


 void addRows(){
       TableRow tblRow=getTableRow();
       tblLayout.addView(tblRow);
      
    }
  TableRow getTableRow(){
      TableRow tblRow=null;
      tblRow=(TableRow)inflater.inflate(R.layout.table_row, null);
      TextView tvName=(TextView) tblRow.findViewById(R.id.tvName);
      tvName.setText("Pizza ");
      TextView tvPrice=(TextView) tblRow.findViewById(R.id.tvPrice);
      tvPrice.setText("$ 10.0");
      ImageView editImageView=(ImageView)tblRow.findViewById(R.id.ivEdit);
      editImageView.setTag("edt");
      editImageView.setOnClickListener(this);
      ImageView deleteImageView=(ImageView)tblRow.findViewById(R.id.ivDelete);
      deleteImageView.setTag("del");
      deleteImageView.setOnClickListener(this);
      return tblRow;
     
   }


Setp 2: getTag from clicked view and use "unique" vale of tag for matching view and perform your desire action.

public void onClick(View v) {
String tag=v.getTag().toString();
if(tag.startsWith("edt")){
    Toast.makeText(this, "Edit Action", Toast.LENGTH_SHORT).show();
  
}else{
    Toast.makeText(this, "Delete Action", Toast.LENGTH_SHORT).show();
}
  
}


you can enjoy simple project from here.

Regards

Imran ali