Android Fragment not replacing UI from Activity - java

I am currently building an android application that uses a navigation drawer. When the user selects an item from the drawer, a fragment is created that corresponds to the item selected. For example, if the user selects the contacts item from the navigation drawer, the UI should change from the dashboard, to the contacts layout.
I am successfully creating fragments, however the Fragment retains the calenderView from my dashboard.
Here is the dashboard layout:
Here is the Dashboard layout
Here is the layout once the user selects timer from the navigation drawer
enter image description here
The problem is that the calenderView remains when the fragment is inflated. Ideally it would just be the "Timer Frag" Button that is visible in this fragment.
Here is my mainActivity code:
//Fragments will be inflated through this method.
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
Fragment fragment = null;
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_patient) {
fragment = new Patient_Fragment();
// Handle the camera action
} else if (id == R.id.nav_timer) {
fragment = new Timer_Fragment();
} else if (id == R.id.nav_reminders) {
} else if (id == R.id.nav_contacts) {
} else if (id == R.id.nav_account) {
} else if (id == R.id.nav_about) {
}
if(fragment !=null)
{
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.replace(R.id.dashboardArea, fragment);
ft.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
Here is my timer Fragment:
public class Timer_Fragment extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_timer, null);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
}
Here is the fragment XML:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
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:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/timerFrag"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="8dp"
android:text="Timer Frag"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.181" />
This is the dashboard XML:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
android:id="#+id/dashboardArea"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.a517086.carefree.MainActivity"
tools:showIn="#layout/app_bar_main">
<CalendarView
android:id="#+id/calendarView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</FrameLayout>

The problem is you are replacing the R.id.dashboardArea (which is in your CalendarView fragment layout), but you need to replace the View in your MainActivity which will hold the fragment. I have called it content_container for this example.
if(fragment !=null)
{
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.replace(R.id.content_container, fragment);
ft.commit();
}
Example:
I use a DrawerLayout, but you can use just any layout. This is my MainActivity Layout.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
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:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<RelativeLayout
android:id="#+id/content_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
</RelativeLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer"/>
</android.support.v4.widget.DrawerLayout>
When I want to swap out my fragments I just get the fragment object I want to be visible and replace the container--In this case "content_container".

You should put your CalendarView in another xml fragment related to the calendar fragment like you did with the timer fragment like this :
fragment_calendar.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
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:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<CalendarView
android:id="#+id/calendarView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
CalendarFragment.java
public class CalendarFragment extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_calendar, null);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
}
Your dashboard xml file should be empty like this :
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
android:id="#+id/dashboardArea"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.a517086.carefree.MainActivity"
tools:showIn="#layout/app_bar_main">
</FrameLayout>
Then, in your main activity initialize the calendar fragment just like that :
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.add(R.id.dashboardArea, CalendarFragment);
ft.commit();

Related

First fragment remains in the background after transition

I am currently trying to create an app having a splash screen, a login screen and a register screen.
The only way to achieve exactly what I need is through fragments. Though when I try to transition from the splash screen to the login fragment the text view which was part of the splash screen remains. The same happens after transitioning from the login fragment to the register fragment as well as from the register fragment back to the login fragment. It is important to note that there is no issue during transitioning between login and register or between register and login - except the fact that the edit text stays there.
My MainActivity.java
public class StartActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
}
#Override
public void onBackPressed(){
Toast.makeText(getApplicationContext(), "Back button is disabled", Toast.LENGTH_SHORT).show();
}
}
My layout for MainActivity
<?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=".StartActivity"
android:background="#mipmap/background">
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/viewpagerstart"
android:layout_centerInParent="true"
android:name="com.example.distributedsystemsui.SplashFragment">
</fragment>
</RelativeLayout>
The SplashScreen.java
public class SplashFragment extends Fragment {
LinearLayout linearLayout;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_splash, container, false);
linearLayout = (LinearLayout) view.findViewById(R.id.f_linearsplash);
Animation animation_fadein = AnimationUtils.loadAnimation((StartActivity)getActivity(), R.anim.fade_in);
linearLayout.startAnimation(animation_fadein);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.setCustomAnimations(R.anim.slide_enter_left, R.anim.slide_exit_left,
R.anim.slide_enter_right, R.anim.slide_exit_right);
LoginFragment loginFragment = LoginFragment.newInstance();
ft.replace(R.id.viewpagerstart, loginFragment);
ft.commit();
}
}, 3000);
return view;
}
}
And the layout for the SplashScreen fragment.
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".LoginFragment"
android:background="#color/Tranparent"
android:id="#+id/frame_splash">
<LinearLayout
android:id="#+id/f_linearsplash"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="#+id/f_splashlogo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="70dp"
android:background="#FFFFFF"/>
<TextView
android:id="#+id/f_splashtext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/app_name"
android:layout_gravity="center_horizontal"
android:layout_marginTop="100dp"
android:background="#FFFFFF"/>
</LinearLayout>
</FrameLayout>
All my search led back to nothing.
I can only assume that either the below contained in the MainActivity.xml creates a confusion (which I tried to change but no luck):
android:name="com.example.distributedsystemsui.SplashFragment"
or that I am doing a mistake in the SplashScreen.java that I cannot locate, even though I tried for more than 5 hours to make it work.
The problem is that you cannot replace fragments added via the <fragment> tag.
Instead, you should either:
1) Switch to FragmentContainerView, which was added in Fragment 1.2.0. It does not suffer from the same issue as the <fragment> tag and lets you do replace operations without issues:
<?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=".StartActivity"
android:background="#mipmap/background">
<androidx.fragment.app.FragmentContainerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/viewpagerstart"
android:layout_centerInParent="true"
android:name="com.example.distributedsystemsui.SplashFragment">
</androidx.fragment.app.FragmentContainerView>
</RelativeLayout>
2) Use a FrameLayout in your layout and manually add the SplashFragment in your activity (this is essentially what FragmentContainerView does for you):
<?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=".StartActivity"
android:background="#mipmap/background">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/viewpagerstart"
android:layout_centerInParent="true">
</FrameLayout>
</RelativeLayout>
which means you need to add the SplashFragment manually:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.viewpagerstart, new SplashFragment())
.commit()
}
}
I think it is better to do the fragment transactions from your activity instead of doing it from your fragment. You might consider having functions in your MainActivity as follows.
public class StartActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
}
public void goToLoginFragment() {
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.setCustomAnimations(R.anim.slide_enter_left, R.anim.slide_exit_left,
R.anim.slide_enter_right, R.anim.slide_exit_right);
LoginFragment loginFragment = LoginFragment.newInstance();
ft.replace(R.id.viewpagerstart, loginFragment);
ft.commit();
}
public void goToRegisterFragment() {
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.setCustomAnimations(R.anim.slide_enter_left, R.anim.slide_exit_left,
R.anim.slide_enter_right, R.anim.slide_exit_right);
LoginFragment registerFragment = RegisterFragment.newInstance();
ft.replace(R.id.viewpagerstart, registerFragment);
ft.commit();
}
#Override
public void onBackPressed(){
Toast.makeText(getApplicationContext(), "Back button is disabled", Toast.LENGTH_SHORT).show();
}
}
And then from your SplashFragment call the function that is defined in your activity.
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
((MainActivity) getActivity()).goToLoginFragment();
}
}, 3000);
I hope that solves the problem.

TextView.setView() does not update text

From a fragment I start an activty, that opens a new fragment. Also I pass a string value from the first fragment (AllDishes) over the activity to the last fragment (DishDetailView) via intent.
The fragment (DishDetailView) is set as context to a layout (fragment_dishdetailview), but when I try to set the text that was passed, the view is not getting updated.
When I debug my app, the string parameter ("Test") seems to be passed and also the text of the TextView name seems to be set correctly, as you can see in the screenshot below, but somehow the UI (fragment_dishdetailview) is not getting updated, it´s just empty.
I´m not sure whether the update of the UI or the way of passing the value from one fragment to another is the problem. My aim is to open the fragment (DishDetailView) from fragment (AllDishes) and pass a string from the first to the second fragment. So actually I don´t need the activity but without I was not able to pass the String.
AllDishes (fragment)
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Dish dish = ca.getItem(position);
Intent intent = new Intent(rootView.getContext(), DishDetailsViewActivity.class);
intent.putExtra("nameToPass" , dish.name);
startActivity(intent);
}
DishDetailView (fragment)
public class DishDetailView extends Fragment {
public View onCreateView(
LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState
) {
View rootView = inflater.inflate(R.layout.fragment_dishdetailview, container, false);
String tempHolder = getActivity().getIntent().getStringExtra("nameToPass");
TextView name = rootView.findViewById(R.id.textview_view_dishName);
name.setText(tempHolder);
rootView.invalidate();
return inflater.inflate(R.layout.fragment_dishdetailview, container, false);
}
}
DishDetailsViewActivity (activity)
public class DishDetailsViewActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dish_details_view);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
}
fragment_dishdetailview.xml (fragment layout)
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
android:background="#color/screen_background"
tools:context=".fragments.DishDetailView">
<TextView
android:id="#+id/textview_view_dishName"
android:layout_width="300dp"
android:layout_height="27dp"
android:layout_marginStart="24dp"
android:layout_marginLeft="24dp"
android:layout_marginTop="20dp"
android:textColor="#color/headercolor"
android:textSize="#dimen/header_fontsize"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
** content_dish_details_view.xml (activity layout)**
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<fragment
android:id="#+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="0dp"
android:layout_height="0dp"
app:defaultNavHost="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:navGraph="#navigation/nav_graph3" />
</androidx.constraintlayout.widget.ConstraintLayout>
nav-graph.xml
<?xml version="1.0" encoding="utf-8"?>
<navigation 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:id="#+id/nav_graph3"
app:startDestination="#id/fragment_dishdetailview">
<fragment
android:id="#+id/fragment_dishdetailview"
android:name="com.example.nutritracker.fragments.DishDetailView"
android:label="DishDetailView"
tools:layout="#layout/fragment_dishdetailview">
</fragment>
</navigation>
I think you should return your rootView on the onCreateView method of DishDetailView.

I am trying open a Fragment From onOptionsItemSelected Method

I am trying to call a fragment from an activity. But unable. This is what I tried.
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (item.getItemId()==R.id.action_search){
SearchFragment searchFragment=new SearchFragment();
getSupportFragmentManager().beginTransaction().add(R.id.container,searchFragment,null).commit();
}
return true;
}
And My main_activity.xml
<androidx.appcompat.widget.LinearLayoutCompat xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/container"
tools:context=".Controllers.MainActivity">
After trying the app does crash but its also not opening the fragment which I want.
The fragment xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/searchFragment"
tools:context=".SearchFragment">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerViewSearchFrag"
android:layout_width="match_parent"
android:layout_height="match_parent">
</androidx.recyclerview.widget.RecyclerView>
And Fragment java is
public class SearchFragment extends Fragment {
private RecyclerView mRecyclerViewSearch;
private RecyclerViewAdpater mAdpater;
public SearchFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_search, container, false);
mRecyclerViewSearch=view.findViewById(R.id.recyclerViewSearchFrag);
mRecyclerViewSearch.setLayoutManager(new LinearLayoutManager(getContext()));
mAdpater=new RecyclerViewAdpater(DataSevices.mChineseColors,getActivity());
return view;
}
}
Please correct me if I am doing anything wrong
You can use Framlayout instead of Linear-layout
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
if you want some other components in your MainActivity , create a fragment for that.
and replace it.
in activity_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/frameLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" />
in your fragment xml:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SearchFragment">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerViewSearchFrag"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
create new fragment fragment_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
...
</LinearLayout>
and MainFragment.java
public class MainFragment extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup
container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
//...
return view;
}
}

Fragments are not getting replaced in the main_activity()

I am trying to make navigation drawer using fragments using the reference link : https://guides.codepath.com/android/Fragment-Navigation-Drawer
But the problem is when i tap on any of the item in navigation drawer it does not replace the corresponding fragment to the main activity layout.
Main activity snippet:
public void selectDrawerItem(MenuItem menuItem) {
// Create a new fragment and specify the fragment to show based on nav item clicked
Fragment fragment = null;
Class fragmentClass;
switch(menuItem.getItemId()) {
case R.id.nav_first_fragment:
//fragmentClass = FirstFragment.class;
fragment=new FirstFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().add(R.id.flContent, fragment).commit();
break;
case R.id.nav_second_fragment:
//fragmentClass = SecondFragment.class;
fragment=new SecondFragment();
FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
tx.replace(R.id.flContent, Fragment.instantiate(MainActivity.this, "com.example.FirstFragment"));
tx.commit();
break;
default:
fragmentClass = FirstFragment.class;
}
activity_main layout:
<!-- This LinearLayout represents the contents of the screen -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!-- The ActionBar displayed at the top -->
<include
layout="#layout/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<!-- The main content view where fragments are loaded -->
<LinearLayout
android:id="#+id/flContent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
/>
</LinearLayout>
<!-- The navigation drawer that comes from the left -->
<!-- Note that `android:layout_gravity` needs to be set to 'start' -->
<android.support.design.widget.NavigationView
android:id="#+id/nvView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:headerLayout="#layout/nav_header"
android:layout_gravity="start"
android:background="#android:color/white"
app:menu="#menu/drawer_view" />
</android.support.v4.widget.DrawerLayout>
fragment one layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Fragment 1"
android:layout_gravity="center"
android:gravity="center"
android:background="#FF5722"/>
</LinearLayout>
frament one java:
public class FirstFragment extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState){
View view = inflater.inflate(R.layout.home, container,false);
if(container==null){
Log.d("First","Null");
return view;
}Log.d("First"," Not Null");
return null;
}
}
use this in switch
switch(menuItem.getItemId()) {
case R.id.nav_first_fragment:
getSupportFragmentManager().beginTransaction().replace(R.id.container, new FirstFragment()).commit();
break;
case R.id.nav_second_fragment:
getSupportFragmentManager().beginTransaction().replace(R.id.container, new SecondFragment()).commit();
break;
}
and make sure you give the correct IDs to the switch. And "container" is the ID for the layout of the activity_main.xml
just give the ID to main Layout like
android:id="#+id/container"

Fragment Not Displaying In Activity

Currently when running my application, going to this activity does not display my fragment. Am I adding the fragment wrong and so nothing in the fragment is displayed? Or is there something wrong the dynamic behavior in the fragment onCreateView method?
My Activity Code
public class AskQuestionActivity extends FragmentActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ask_question);
}
}
My Activity XML
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:layout_width="match_parent"
android:layout_height="match_parent"
android:hint="#string/header_text"/>
<fragment android:name="com.mypackage.AskQuestionFragment"
android:id="#+id/question_fragment"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent" />
</LinearLayout>
My Fragment Code
public class AskQuestionFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
String questionText = "What is your favorite color?";
List<String> answers = Arrays.asList("Red", "Blue", "Yellow");
LinearLayout layout = (LinearLayout)inflater.inflate(R.layout.question, container);
Resources res = getResources();
int id = res.getIdentifier("question_text", "id", layout.getContext().getPackageName());
TextView questionTextView = (TextView)layout.findViewById(id);
questionTextView.setText(questionText);
id = res.getIdentifier("question_answers", "id", layout.getContext().getPackageName());
RadioGroup radioGroup = (RadioGroup)layout.findViewById(id);
Collections.reverse(answers);
for (String s : answers) {
RadioButton button = new RadioButton(layout.getContext());
button.setText(s);
radioGroup.addView(button, 0);
}
return layout;
}
}
My Fragment XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/question_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/question_text"/>
<RadioGroup android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/question_answers"></RadioGroup>
<Button
android:id="#+id/submit_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/submit_button_text"
/>
</LinearLayout>
try to put framelayout instead of fragment in xml. and in your activity's onCreate create the instance of your fragment you want to display and add it to the fragment container
public class AskQuestionActivity extends FragmentActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ask_question);
AskQuestionFragment fragment = new AskQuestionFragment();
getSupportFragmentManager().beginTransaction()
.add(R.id.id_of_your_container, fragment).commit();
}
}
Your problem might be when doing this:
LinearLayout layout = (LinearLayout)inflater.inflate(R.layout.question, container);
Consider to replace that line with one of the following:
LinearLayout layout = (LinearLayout)inflater.inflate(R.layout.question, null);
or
LinearLayout layout = (LinearLayout)inflater.inflate(R.layout.question, container, false);
change your layout from linear to be framelayout, and attach your fragment in activity .
getSupportFragmentManager().beginTransaction()
.add(R.id.your_fragment_container, fragment).commit();

Categories