adding a fragment to activity without actual fragment












0















So, i am doing this for learning purposes,



What exactly i want to do is :



Create two fragments,
First fragment has a button which when pressed replaces the fragment View on the main activity with the second fragment, second fragment just contains a textview saying "This is second fragment" but when i tried to do it,
the first fragment is loaded two times and on button pressed, first instance stays where as the second instance is changed to the second fragment. Can you guys tell me what am i doing wrong : (i am attaching the code as well the the screenshots)



MainActivity.java :



package com.femindharamshi.fragmenttrials;

import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements FirstFragment.OnFragmentInteractionListener {

FragmentTransaction fragmentTransaction;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

fragmentTransaction = getSupportFragmentManager().beginTransaction();
FirstFragment newFrament = new FirstFragment();
fragmentTransaction.add(R.id.fragmentView, newFrament);
fragmentTransaction.commit();

}

@Override
public void onFragmentInteraction() {
Toast.makeText(this, "Button in fragment pressed!", Toast.LENGTH_SHORT).show();
fragmentTransaction = getSupportFragmentManager().beginTransaction();
SecondFragment newFragment = new SecondFragment();
fragmentTransaction.replace(R.id.fragmentView, newFragment);
fragmentTransaction.commit();
}
}


activity_main.xml



<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<fragment
android:id="@+id/fragmentView"
android:name="com.femindharamshi.fragmenttrials.FirstFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"/>
</RelativeLayout>


FirstFragment.java



package com.femindharamshi.fragmenttrials;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

public class FirstFragment extends Fragment {

private OnFragmentInteractionListener mListener;

Button button;

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

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_first, container, false);

button = view.findViewById(R.id.button);

button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onButtonPressed();
}
});

return view;
}

public void onButtonPressed() {
if (mListener != null) {
mListener.onFragmentInteraction();
}
}

@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;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction();
}
}


SecondFragment.java



package com.femindharamshi.fragmenttrials;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


public class SecondFragment extends Fragment {


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


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_second, container, false);
}


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


Problem : Also, without mentioning android:name="com.femindharamshi.fragmenttrials.FirstFragment" in the main activity, the app crashes. What if i don't want to load a fragment when the activity start, why do i have to mention this ? and even if i load secondFragment in this, is it okay ? even though in the name it says FirstFragment?



What if i don't want to assign the in the main activity with a fragment class before hand, and want to do it programmatically ?



Screenshots :



Before Clicking the buttonAfter Clicking the button










share|improve this question

























  • A <fragment> element in your layout is not just a placeholder or container. It actually causes a Fragment to be loaded and added. If you're going to handle your Fragments dynamically, then change the <fragment> to a <FrameLayout>, which will act as a container for the Fragments you're transacting in your code.

    – Mike M.
    Nov 23 '18 at 20:07











  • Oh my god, thank you, solved my issue! So, now imagine my first fragment has a recycler view and when i replace it with the second fragment and .addToBackStack(null); then when i press back will the recycler view be at the same scroll position as before the secondFragment was loaded ?

    – Femn Dharamshi
    Nov 23 '18 at 20:09


















0















So, i am doing this for learning purposes,



What exactly i want to do is :



Create two fragments,
First fragment has a button which when pressed replaces the fragment View on the main activity with the second fragment, second fragment just contains a textview saying "This is second fragment" but when i tried to do it,
the first fragment is loaded two times and on button pressed, first instance stays where as the second instance is changed to the second fragment. Can you guys tell me what am i doing wrong : (i am attaching the code as well the the screenshots)



MainActivity.java :



package com.femindharamshi.fragmenttrials;

import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements FirstFragment.OnFragmentInteractionListener {

FragmentTransaction fragmentTransaction;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

fragmentTransaction = getSupportFragmentManager().beginTransaction();
FirstFragment newFrament = new FirstFragment();
fragmentTransaction.add(R.id.fragmentView, newFrament);
fragmentTransaction.commit();

}

@Override
public void onFragmentInteraction() {
Toast.makeText(this, "Button in fragment pressed!", Toast.LENGTH_SHORT).show();
fragmentTransaction = getSupportFragmentManager().beginTransaction();
SecondFragment newFragment = new SecondFragment();
fragmentTransaction.replace(R.id.fragmentView, newFragment);
fragmentTransaction.commit();
}
}


activity_main.xml



<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<fragment
android:id="@+id/fragmentView"
android:name="com.femindharamshi.fragmenttrials.FirstFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"/>
</RelativeLayout>


FirstFragment.java



package com.femindharamshi.fragmenttrials;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

public class FirstFragment extends Fragment {

private OnFragmentInteractionListener mListener;

Button button;

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

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_first, container, false);

button = view.findViewById(R.id.button);

button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onButtonPressed();
}
});

return view;
}

public void onButtonPressed() {
if (mListener != null) {
mListener.onFragmentInteraction();
}
}

@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;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction();
}
}


SecondFragment.java



package com.femindharamshi.fragmenttrials;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


public class SecondFragment extends Fragment {


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


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_second, container, false);
}


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


Problem : Also, without mentioning android:name="com.femindharamshi.fragmenttrials.FirstFragment" in the main activity, the app crashes. What if i don't want to load a fragment when the activity start, why do i have to mention this ? and even if i load secondFragment in this, is it okay ? even though in the name it says FirstFragment?



What if i don't want to assign the in the main activity with a fragment class before hand, and want to do it programmatically ?



Screenshots :



Before Clicking the buttonAfter Clicking the button










share|improve this question

























  • A <fragment> element in your layout is not just a placeholder or container. It actually causes a Fragment to be loaded and added. If you're going to handle your Fragments dynamically, then change the <fragment> to a <FrameLayout>, which will act as a container for the Fragments you're transacting in your code.

    – Mike M.
    Nov 23 '18 at 20:07











  • Oh my god, thank you, solved my issue! So, now imagine my first fragment has a recycler view and when i replace it with the second fragment and .addToBackStack(null); then when i press back will the recycler view be at the same scroll position as before the secondFragment was loaded ?

    – Femn Dharamshi
    Nov 23 '18 at 20:09
















0












0








0








So, i am doing this for learning purposes,



What exactly i want to do is :



Create two fragments,
First fragment has a button which when pressed replaces the fragment View on the main activity with the second fragment, second fragment just contains a textview saying "This is second fragment" but when i tried to do it,
the first fragment is loaded two times and on button pressed, first instance stays where as the second instance is changed to the second fragment. Can you guys tell me what am i doing wrong : (i am attaching the code as well the the screenshots)



MainActivity.java :



package com.femindharamshi.fragmenttrials;

import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements FirstFragment.OnFragmentInteractionListener {

FragmentTransaction fragmentTransaction;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

fragmentTransaction = getSupportFragmentManager().beginTransaction();
FirstFragment newFrament = new FirstFragment();
fragmentTransaction.add(R.id.fragmentView, newFrament);
fragmentTransaction.commit();

}

@Override
public void onFragmentInteraction() {
Toast.makeText(this, "Button in fragment pressed!", Toast.LENGTH_SHORT).show();
fragmentTransaction = getSupportFragmentManager().beginTransaction();
SecondFragment newFragment = new SecondFragment();
fragmentTransaction.replace(R.id.fragmentView, newFragment);
fragmentTransaction.commit();
}
}


activity_main.xml



<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<fragment
android:id="@+id/fragmentView"
android:name="com.femindharamshi.fragmenttrials.FirstFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"/>
</RelativeLayout>


FirstFragment.java



package com.femindharamshi.fragmenttrials;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

public class FirstFragment extends Fragment {

private OnFragmentInteractionListener mListener;

Button button;

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

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_first, container, false);

button = view.findViewById(R.id.button);

button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onButtonPressed();
}
});

return view;
}

public void onButtonPressed() {
if (mListener != null) {
mListener.onFragmentInteraction();
}
}

@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;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction();
}
}


SecondFragment.java



package com.femindharamshi.fragmenttrials;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


public class SecondFragment extends Fragment {


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


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_second, container, false);
}


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


Problem : Also, without mentioning android:name="com.femindharamshi.fragmenttrials.FirstFragment" in the main activity, the app crashes. What if i don't want to load a fragment when the activity start, why do i have to mention this ? and even if i load secondFragment in this, is it okay ? even though in the name it says FirstFragment?



What if i don't want to assign the in the main activity with a fragment class before hand, and want to do it programmatically ?



Screenshots :



Before Clicking the buttonAfter Clicking the button










share|improve this question
















So, i am doing this for learning purposes,



What exactly i want to do is :



Create two fragments,
First fragment has a button which when pressed replaces the fragment View on the main activity with the second fragment, second fragment just contains a textview saying "This is second fragment" but when i tried to do it,
the first fragment is loaded two times and on button pressed, first instance stays where as the second instance is changed to the second fragment. Can you guys tell me what am i doing wrong : (i am attaching the code as well the the screenshots)



MainActivity.java :



package com.femindharamshi.fragmenttrials;

import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements FirstFragment.OnFragmentInteractionListener {

FragmentTransaction fragmentTransaction;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

fragmentTransaction = getSupportFragmentManager().beginTransaction();
FirstFragment newFrament = new FirstFragment();
fragmentTransaction.add(R.id.fragmentView, newFrament);
fragmentTransaction.commit();

}

@Override
public void onFragmentInteraction() {
Toast.makeText(this, "Button in fragment pressed!", Toast.LENGTH_SHORT).show();
fragmentTransaction = getSupportFragmentManager().beginTransaction();
SecondFragment newFragment = new SecondFragment();
fragmentTransaction.replace(R.id.fragmentView, newFragment);
fragmentTransaction.commit();
}
}


activity_main.xml



<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<fragment
android:id="@+id/fragmentView"
android:name="com.femindharamshi.fragmenttrials.FirstFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"/>
</RelativeLayout>


FirstFragment.java



package com.femindharamshi.fragmenttrials;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

public class FirstFragment extends Fragment {

private OnFragmentInteractionListener mListener;

Button button;

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

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_first, container, false);

button = view.findViewById(R.id.button);

button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onButtonPressed();
}
});

return view;
}

public void onButtonPressed() {
if (mListener != null) {
mListener.onFragmentInteraction();
}
}

@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;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction();
}
}


SecondFragment.java



package com.femindharamshi.fragmenttrials;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


public class SecondFragment extends Fragment {


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


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_second, container, false);
}


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


Problem : Also, without mentioning android:name="com.femindharamshi.fragmenttrials.FirstFragment" in the main activity, the app crashes. What if i don't want to load a fragment when the activity start, why do i have to mention this ? and even if i load secondFragment in this, is it okay ? even though in the name it says FirstFragment?



What if i don't want to assign the in the main activity with a fragment class before hand, and want to do it programmatically ?



Screenshots :



Before Clicking the buttonAfter Clicking the button







java android android-fragments






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 23 '18 at 20:08







Femn Dharamshi

















asked Nov 23 '18 at 20:00









Femn DharamshiFemn Dharamshi

50113




50113













  • A <fragment> element in your layout is not just a placeholder or container. It actually causes a Fragment to be loaded and added. If you're going to handle your Fragments dynamically, then change the <fragment> to a <FrameLayout>, which will act as a container for the Fragments you're transacting in your code.

    – Mike M.
    Nov 23 '18 at 20:07











  • Oh my god, thank you, solved my issue! So, now imagine my first fragment has a recycler view and when i replace it with the second fragment and .addToBackStack(null); then when i press back will the recycler view be at the same scroll position as before the secondFragment was loaded ?

    – Femn Dharamshi
    Nov 23 '18 at 20:09





















  • A <fragment> element in your layout is not just a placeholder or container. It actually causes a Fragment to be loaded and added. If you're going to handle your Fragments dynamically, then change the <fragment> to a <FrameLayout>, which will act as a container for the Fragments you're transacting in your code.

    – Mike M.
    Nov 23 '18 at 20:07











  • Oh my god, thank you, solved my issue! So, now imagine my first fragment has a recycler view and when i replace it with the second fragment and .addToBackStack(null); then when i press back will the recycler view be at the same scroll position as before the secondFragment was loaded ?

    – Femn Dharamshi
    Nov 23 '18 at 20:09



















A <fragment> element in your layout is not just a placeholder or container. It actually causes a Fragment to be loaded and added. If you're going to handle your Fragments dynamically, then change the <fragment> to a <FrameLayout>, which will act as a container for the Fragments you're transacting in your code.

– Mike M.
Nov 23 '18 at 20:07





A <fragment> element in your layout is not just a placeholder or container. It actually causes a Fragment to be loaded and added. If you're going to handle your Fragments dynamically, then change the <fragment> to a <FrameLayout>, which will act as a container for the Fragments you're transacting in your code.

– Mike M.
Nov 23 '18 at 20:07













Oh my god, thank you, solved my issue! So, now imagine my first fragment has a recycler view and when i replace it with the second fragment and .addToBackStack(null); then when i press back will the recycler view be at the same scroll position as before the secondFragment was loaded ?

– Femn Dharamshi
Nov 23 '18 at 20:09







Oh my god, thank you, solved my issue! So, now imagine my first fragment has a recycler view and when i replace it with the second fragment and .addToBackStack(null); then when i press back will the recycler view be at the same scroll position as before the secondFragment was loaded ?

– Femn Dharamshi
Nov 23 '18 at 20:09














0






active

oldest

votes











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53452354%2fadding-a-fragment-to-activity-without-actual-fragment%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes
















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53452354%2fadding-a-fragment-to-activity-without-actual-fragment%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Costa Masnaga

Fotorealismo

Sidney Franklin