我在Activtiy的这一部分(SearchActivity.java)中收到错误:
// Whenever a view in your cart is clicked
shoppinListAdapter.SetOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
Utils.switchFragmentWithAnimation(
R.id.frag_container,
new ProductDetailsFragment("", position, true),
((ECartHomeActivity) (getContext())), null,
Utils.AnimationType.SLIDE_LEFT);
// ECartHomeActivity is the MainActivity
}
});
这是Utils类的方法,它在Activity:
中使用public static void switchFragmentWithAnimation(int id, Fragment fragment,
FragmentActivity activity, String TAG, AnimationType transitionStyle) {
FragmentManager fragmentManager = activity.getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
if (transitionStyle != null) {
switch (transitionStyle) {
case SLIDE_UP:
// Enter from Up
fragmentTransaction.setCustomAnimations(R.anim.slide_in_up,
R.anim.slide_out_up);
break;
case SLIDE_LEFT:
// Enter from left
fragmentTransaction.setCustomAnimations(R.anim.slide_left,
R.anim.slide_out_left);
break;
default:
break;
}
}
CURRENT_TAG = TAG;
fragmentTransaction.replace(id, fragment);
fragmentTransaction.addToBackStack(TAG);
fragmentTransaction.commit();
}
此代码我将我的一个片段粘贴到此Searched_Product_Activtiy.java中。它在片段中工作正常。
答案 0 :(得分:1)
问题是您是否正在尝试将ECartHomeActivity转换为((ECartHomeActivity) (getContext())
的上下文,因为它不是Activity实例,所以它不起作用。
您可以使用SearchActivity.this
作为Util的活动,但将activity
参数更改为活动,如下所示:
public static void switchFragmentWithAnimation(int id, Fragment fragment,
Activity activity, String TAG, AnimationType transitionStyle) {
}
但那可能不是你想要的,我想你想在MainActivity中切换片段。如果这是您的意图,则应使用MainActivity中的startActivityForResult()
。为此,首先需要从MainActivity启动ActivitySearch:
public static final int REQUEST_CODE = 1;
...
public void startSearch() {
Intent intent=new Intent(MainActivity.this, ActivitySearch.class);
startActivityForResult(intent, REQUEST_CODE);
}
其次,在MainActivity中覆盖onActivityResult()
以从ActivitySearch接收结果:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == REQUEST_CODE) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
// Call your util here
Utils.switchFragmentWithAnimation(
R.id.frag_container,
new ProductDetailsFragment("", position, true),
MainActivity.this, null,
Utils.AnimationType.SLIDE_LEFT);
}
}
}
最后,在ActivitySearch中,每当您点击搜索中的项目时,您需要将结果发送到MainActivity:
shoppinListAdapter.SetOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
Intent intent=new Intent();
// send data if you want
//intent.putExtra("DATA", yourdata);
setResult(MainActivity.REQUEST_CODE, intent);
finish(); // close the SearchActivity
}