Android: error with on fragment interaction Listener
I’ve removed useless references and everything related with RecommendedFragment class. If you post it I will update my answer.
I’ve tested it and it works. But try to explain what is the meaning of openHome() method, because it is never used based on your code, and nevertheless you say that the app crashes when you call it.
I added this method to the interface because it seems to me the most logical thing to do.
//MainActivity
public class MainActivity extends Activity implements HomeFragment.OnFragmentInteractionListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getFragmentManager().beginTransaction()
.add(R.id.mainFrame, new HomeFragment())
.commit();
}
@Override
public void openHome(View view) {
System.out.println("Success");
}
@Override
public void onFragmentInteractionHome(Uri uri) {
Toast.makeText(this, "Success", Toast.LENGTH_SHORT).show();
}
}
//HomeFragment
public class HomeFragment extends Fragment {
private OnFragmentInteractionListener mListener;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_home, container, false);
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteractionHome(uri);
}
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
mListener.onFragmentInteractionHome(Uri.parse("doWhatYouWant"));
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
public void onFragmentInteractionHome(Uri uri);
public void openHome(View view);
}
}