user3227070 user3227070 - 4 months ago 25
Android Question

Set fragment as layout on activity start

MainActivity.java:

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new homePage())
.commit();
}
}
}


Here is the error which I got:


Cannot resolve method add(int, etc...) on line add(R.id.container, new
homePage())


So basically i created three fragments and one activity. My activity does not have a lay-out (though it does obviously have a layout page, it's ID is container). I want to add the homePage layout file to the container when the activity starts, but this doesn't seem to be working. I've only created the layout etc so far, and now I'm trying to add the java code but I'm unsure why this isn't working.

I haven't edited the java code of any of the fragments yet so it's basically the code android studio adds to it on creation.

public class homePage extends Fragment {

private OnFragmentInteractionListener mListener;
private View view;

public homePage() {
// Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_home_page, container, false);
Button btnLogin = (Button) view.findViewById(R.id.login);
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
loginView();
}
});
return view;
}

public static homePage newInstance() {
homePage fragment = new homePage();
Bundle args = new Bundle();
return fragment;
}

public void loginView(){}

@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}

@Override
public void onDetach() {
super.onDetach();
mListener = null;
}

/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}

Answer

This might be because your homeFragment extends the Fragment from the support library (android.support.v4.app.Fragment) and hence your MainActivity should use getSupportFragmentManager() instead of getFragmentManager() which is a part of android.app.Fragment.

Comments