剛開始邊學習邊開發,錯誤之處請指正
最近在項目中遇到Android監聽事件需要傳參的問題
比如,在ListView中,一些不定的資料有CheckBox,要通過點擊勾選在下方顯示出來,故而在監聽 setOnClickListener 事件中,需要帶入一些參數來控制
最後想到的方式是不通過預設的監聽類
[java] holder.cbNode.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
}
});
holder.cbNode.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
}
});
,自己寫一個監聽類實現監聽介面,構造帶參數的建構函式來做,如下所示:
[java] class CheckBoxListener implements OnClickListener{
private TextView _tvPeople = null;
private ViewHolder _holder = null;
public CheckBoxListener(TextView tvPeople, ViewHolder holder)
{
// TODO Auto-generated constructor stub
this._tvPeople = tvPeople;
this._holder = holder;
}
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
if(this._holder.cbNode!=null)
{
String curSelectedPeople = this._tvPeople.getText().toString();
if(!this._holder.cbNode.isChecked())
{
//取消以選擇的閱辦人
curSelectedPeople = (","+curSelectedPeople).replace(","+this._holder.cbNode.getText().toString(), "").substring(1);
this._tvPeople.setText(curSelectedPeople);
}else
{
//顯示增加的閱辦人
if(!curSelectedPeople.equals(""))
curSelectedPeople+= ","+this._holder.cbNode.getText().toString();
else
curSelectedPeople = this._holder.cbNode.getText().toString();
_tvPeople.setText(curSelectedPeople);
}
}
}
}
class CheckBoxListener implements OnClickListener{
private TextView _tvPeople = null;
private ViewHolder _holder = null;
public CheckBoxListener(TextView tvPeople, ViewHolder holder)
{
// TODO Auto-generated constructor stub
this._tvPeople = tvPeople;
this._holder = holder;
}
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
if(this._holder.cbNode!=null)
{
String curSelectedPeople = this._tvPeople.getText().toString();
if(!this._holder.cbNode.isChecked())
{
//取消以選擇的閱辦人
curSelectedPeople = (","+curSelectedPeople).replace(","+this._holder.cbNode.getText().toString(), "").substring(1);
this._tvPeople.setText(curSelectedPeople);
}else
{
//顯示增加的閱辦人
if(!curSelectedPeople.equals(""))
curSelectedPeople+= ","+this._holder.cbNode.getText().toString();
else
curSelectedPeople = this._holder.cbNode.getText().toString();
_tvPeople.setText(curSelectedPeople);
}
}
}
}如上所示,這裡我在建構函式中,提供了兩個參數,一個TextView(要顯示的控制項),一個是參數對象類,可以很方便的自訂動作.