- 例如我的“極簡天氣”項目中的城市列表的適配器中需要將點擊的城市名稱傳給天氣信息界面的Activity中蛔琅,城市列表是在一個Fragment中加載的,所以可以在城市列表的適配器(CityListAdapter)中寫一個公用的接口奈辰,如下:
private CallBack mCallback;
public CityListAdapter (CallBack callback) {
this.mCallback = callback;
}
public interface CallBack {
public void getCityName(String cityname);
}
然后在此類中將點擊的城市信息獲取到并調(diào)用接口CallBack
中的方法getCityName
傳入cityname
中栏妖,如下:
viewHolder.llMain.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//點擊全部城市響應(yīng)
if(mCallback!=null){
mCallback.getCityName(mAllCityList.get(position).getName());
}else{
Log.e("mcallback-->", "null");
}
}
});
此時,要先在應(yīng)用此適配器的listFragment中實例化CityListAdapter奖恰,并接收接口的數(shù)據(jù)吊趾,即城市信息:
private CallBack mCallback;
public listFragment(CallBack callback) {
this.mCallback = callback;
}
cityListAdapter = new CityListAdapter(getActivity(), allCityList,
hotCityList, new CallBack() {
@Override
public void getCityName(String cityname) {
// TODO Auto-generated method stub
if (cityname != null) {
mCallback.getCityName(cityname);
onBackkey();
} else {
Log.e("null", "kong");
}
}
});
然后在activity中實例化listFragment宛裕,并接收城市信息:
transaction.replace(R.id.weather_layout, new listFragment(
new CallBack() {
@Override
public void getCityName(String cityname) {
tempCity = cityname;
showWeather();
}
}));
若listFragment中另外一個適配器SearchResultAdapter也要傳遞數(shù)據(jù)給activity,則在SearchResultAdapter中:
public SearchResultAdapter (CallBack callback) {
this.mCallback = callback;
}
viewHolder.tvCityName.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mCallback.getCityName(mSearchList.get(position).getName());
}
});
然后以相同方式在listFragment中接收:
private CallBack mCallback;
public listFragment(CallBack callback) {
this.mCallback = callback;
}
注:先創(chuàng)建一個接口的對象mCallback论泛,然后再創(chuàng)建listFragment的構(gòu)造方法揩尸,之后在下面才可以使用mCallback來調(diào)用接口的方法,即mCallback.getCityName(cityname);
searchResultAdapter = new SearchResultAdapter(getActivity(),
searchCityList, new CallBack() {
@Override
public void getCityName(String cityname) {
// TODO Auto-generated method stub
mCallback.getCityName(cityname);
onBackkey();
}
});
注:接口是一個公用的傳遞數(shù)據(jù)的工具屁奏,若要傳遞的數(shù)據(jù)類型相同岩榆,則只需在一個類中寫一次,即可在此包中所用的類使用坟瓢,但不能跳類傳遞勇边,若A類中包含B類,B類中包含C類折联,要將C中的數(shù)據(jù)傳給A類粒褒,只能先給B再給A