67、activity中调用fragment内部自定义的方法

时间:2022-05-04 00:16:08

fragment:

/**
* author: Created by zzl on 15/11/19.
*/
@SuppressLint("validFragment")
public class pushMealHistoryFragment extends Fragment { Context ctxt;
View gridALl;
public pushMealHistoryFragment(Context ctxt)
{
this.ctxt = ctxt;
} @Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { gridALl = inflater.inflate(R.layout.fragment_push_meal_history, null); return gridALl;
} public void updateGridview()
{
final GridView gridviewHistory = (GridView)gridALl.findViewById(R.id.gridview_pushing_history);
final Button btnBackground = (Button)gridALl.findViewById(R.id.empty_meal_done_history_gridview); ApisManager.getMealPushedHistory(CommonUtils.getFormatDate(0), new ApiCallback() {
@Override
public void success(final Object object) { getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
HandlerUtils.showToast(ctxt, "hello,i'm refreshing...");
List<PushHistoryFood> list = (List<PushHistoryFood>) object;
PushHistoryAdapterr adapter = new PushHistoryAdapterr(ctxt, list);
gridviewHistory.setAdapter(adapter);
if (list.size() == 0) {
btnBackground.setVisibility(View.VISIBLE);
} else {
btnBackground.setVisibility(View.INVISIBLE);
}
}
}); } @Override
public void error(BaseApi.ApiResponse response) { }
});
} }

如果要在activity中调用上面的fragment的updateGridview方法,demo:

/**
* author: Created by zzl on 15/11/19.
*/
public class PushMealActivity extends BaseActivity { @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mealdone);
init();
} public void init()
{ Fragment fragmentPushMealHistory = new pushMealHistoryFragment(ctxt);
//在这里调用fragmentPushMealHistory的updateGridview方法
((pushMealHistoryFragment)fragmentPushMealHistory).updateGridview(); } }

2015.11.27更新:

根本原因是fragmentPushMealHistory定义的类型为Fragment,如果为pushMealHistoryFragment,则不需要做强制转换了