Why framentTransaction.commit doesn't work? - android

I'm trying to change the content of my content_navegacao.xml using fragments, but the commit appears to be not functional.
I created a project with a empty activity layout, after i created a navigation drawer activity and i'm trying to change the content of my fragment inside the navigation drawer layout. My transaction is managed inside Navigation_Drawer activity. I think, maybe the imports used in this case could be
responsible for this, because the Navigation Drawer Layout extends AppCompactAcivity class.
I did something like:
Create fragment inside content_navegacao:
<?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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="receitas.cleiton.com.br.receitas.Navegacao_Activity"
tools:showIn="#layout/app_bar_navegacao_">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/container_conteudo">
</LinearLayout>
</RelativeLayout>
Create Fragment Layout -> fragment_home.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ff0000">
</LinearLayout>
Create Fragment class
package receitas.cleiton.com.br.receitas;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Home_Fragment extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home,null);
return view;
}
}
Finally, i made the last implemtations on my NavigationDrawerAcitvity class:
The Activity becomes like:
package receitas.cleiton.com.br.receitas;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
public class Navegacao_Activity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
FragmentManager fm = getSupportFragmentManager();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navegacao_);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) 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();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
if(savedInstanceState == null){
Home_Fragment home_fragment = new Home_Fragment();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.add(R.id.container_conteudo,home_fragment,"home");
fragmentTransaction.addToBackStack("stack");
fragmentTransaction.commit();
}
}
But... when the activity is loaded, nothing happens.
Any Idea?

Try it after if(savedInstanceState == null){ without local variables.
getSupportFragmentManager().beginTransaction().replace(fragment, R.id.container, "home").addToBackStack("tag").commit();
P.S.I would not recommend to initialize variables immediately after their announcement. Do it in the onCreate () method ;

Related

Why does my app won't inflate navigation view class?

I've been making a drawer menu for my home activity, but everytime i tried to run it, it always shows this exception :
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.rplgdc.rekrutmenrpl/com.rplgdc.rekrutmenrpl.Activity.HomeActivity}: android.view.InflateException: Binary XML file line #22: Error inflating class android.support.design.widget.NavigationView
I've been reading previous threads, and mostly it was caused by the appcompat and design library in the gradle doesn't match. But i've checked mine and it's matched from one and other.
Here's a few codes that i have.
activity_home.xml file
<?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/lyt_parent_drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start"
tools:context=".Activity.HomeActivity">
<android.support.design.widget.CoordinatorLayout
android:id="#+id/home_main_content"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include layout="#layout/activity_home_content"/>
</android.support.design.widget.CoordinatorLayout>
<android.support.design.widget.NavigationView
android:id="#+id/menu_drawer"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="false"
app:headerLayout="#layout/layout_menu_header"
app:itemIconTint="#color/grey_40"
app:itemTextColor="#color/grey_90"
app:menu="#menu/item_drawer_menu"/>
</android.support.v4.widget.DrawerLayout>
HomeActivity.java file
package com.rplgdc.rekrutmenrpl.Activity;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.rplgdc.rekrutmenrpl.Adapter.TodaysInputAdapter;
import com.rplgdc.rekrutmenrpl.R;
import java.util.ArrayList;
public class HomeActivity extends AppCompatActivity {
private static final String TAG = "HomeActivity";
private Toolbar toolbar;
private RecyclerView rv;
private TodaysInputAdapter rvAdapter;
private LinearLayout allInputs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_update);
initToolbar();
allInputs= findViewById(R.id.btn_all_inputs);
allInputs.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(HomeActivity.this, InputsListActivity.class));
}
});
rv = findViewById(R.id.rv_todays_input);
rv.setHasFixedSize(true);
rv.setLayoutManager(new LinearLayoutManager(this));
rvAdapter = new TodaysInputAdapter(dummyData(), this, 0);
rv.setAdapter(rvAdapter);
initNavigationMenu();
}
private void initToolbar(){
toolbar = findViewById(R.id.toolbar_home);
setSupportActionBar(toolbar);
}
private void initNavigationMenu() {
NavigationView navigationView = findViewById(R.id.menu_drawer);
final DrawerLayout drawer= findViewById(R.id.lyt_parent_drawer);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close){
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
drawer.setDrawerListener(toggle);
toggle.syncState();
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Toast.makeText(getApplicationContext(), item.getTitle() + " selected", Toast.LENGTH_SHORT).show();
drawer.closeDrawers();
return true;
}
});
drawer.openDrawer(GravityCompat.START);
}
private ArrayList<String> dummyData(){
// just a code for returning a local data for the recycler view
}
}
My Gradle dependencies
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support:design:27.1.1'
implementation 'com.android.support:cardview-v7:27.1.1'
implementation 'com.android.support:recyclerview-v7:27.1.1'
implementation 'com.android.support:support-v13:27.1.1'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.android.support:support-vector-drawable:27.1.1'
If you want more of my codes i will provide it for you to see, any help would be appreciated.
it looks like in file activity_home.xml you are refering to same file. try to remove below line and try to build app:
<include layout="#layout/activity_home"/>

How can I implement my custom toolbar in my Fragment

I read so much article and watched so many videos but I still don't know, how to set up an action bar in an Fragment. I have a activity X with an custom toolbar and one navigation view on the top left(the toolbar is separated in an xml file), I import it in the xml for the activity X.
Here is my toolbar in one single xml:
<?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/drawerChooser"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/new_gradients"
android:fitsSystemWindows="true"
tools:context=".ChoosingActivity">
<!--tools:openDrawer="start"-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimary"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
</LinearLayout>
<FrameLayout
android:id="#+id/fragment_container_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/header"
app:menu="#menu/drawer_menu">
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
EDIT, new toolbar:
<LinearLayout 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"
xmlns:tools="http://schemas.android.com/tools"
android:background="#drawable/new_gradients"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimary"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/new_gradients"
android:fitsSystemWindows="true"
tools:context=".ChoosingActivity">
<FrameLayout
android:id="#+id/fragment_container_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.v4.widget.DrawerLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/header"
app:menu="#menu/drawer_menu">
</android.support.design.widget.NavigationView>
</LinearLayout>
</LinearLayout>
Here is my activity X:
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class ChoosingActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawer;
public void userChoosed(View view) {
Intent choosedIntent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(choosedIntent);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choosing);
Toolbar toolbar = findViewById(R.id.toolbarxml);
setSupportActionBar(toolbar);
drawer = findViewById(R.id.drawerChooser);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
// Item will be Selected
switch (item.getItemId()) {
case R.id.nav_meetings:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new Ausstehende_Treffen_Fragment()).commit();
break;
case R.id.nav_finished_meetings:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new Abgeschlossene_Treffen_Fragment()).commit();
break;
case R.id.nav_rate:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new Treffen_Bewerten_Fragment()).commit();
break;
case R.id.nav_edit_profile:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new Profil_Bearbeiten_Fragment()).commit();
break;
case R.id.nav_settings:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new Einstellungen_Fragment()).commit();
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
}
EDIT, new activity X ( look at my comment "Toolbar_chooser or toolbar"):
public class ChoosingActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawer;
public void userChoosed(View view) {
Intent choosedIntent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(choosedIntent);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choosing);
Toolbar toolbar = findViewById(R.id.toolbar_chooser); // Toolbar_chooser or toolbar?
setSupportActionBar(toolbar);
drawer = findViewById(R.id.drawerChooser);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
// Item will be Selected
switch (item.getItemId()) {
case R.id.nav_meetings:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container_toolbar, new Ausstehende_Treffen_Fragment()).commit();
break;
case R.id.nav_finished_meetings:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container_toolbar, new Abgeschlossene_Treffen_Fragment()).commit();
break;
case R.id.nav_rate:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container_toolbar, new Treffen_Bewerten_Fragment()).commit();
break;
case R.id.nav_edit_profile:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container_toolbar, new Profil_Bearbeiten_Fragment()).commit();
break;
case R.id.nav_settings:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container_toolbar, new Einstellungen_Fragment()).commit();
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
}
And here my Fragment where I want to add the toolbar with the navigation view:
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
public class Ausstehende_Treffen_Fragment extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_ausstehende_treffen,container,false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
((AppCompatActivity)getActivity()).getSupportActionBar(toolbar); // HOW???
}
}
EDIT, new Fragment:
public class Ausstehende_Treffen_Fragment extends Fragment {
// Toolbar toolbar = (Toolbar) getActivity().findViewById(R.id.toolbarreal);
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_ausstehende_treffen,container,false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
Toolbar toolbar = ((ChoosingActivity)getActivity()).findViewById(R.id.toolbar_ausstehende_treffen);
}
}
Here is also my xml for the fragment, where I want to have the toolbar:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/holo_orange_light">
<include
android:id="#+id/toolbar_ausstehende_treffen"
layout= "#layout/toolbar"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ausstehende Treffen Fragment"
android:textSize="25sp"
android:layout_centerInParent="true"/>
</RelativeLayout>
Im not able anymore to open my navigation bar in my choosing activity and I don't know why..
I include the toolbars manually in the xml files, its necessary right? + some code in the fragment itself. Man I hope you understand my code and my problems. Pls help me I just want to keep my custom toolbar in any fragment and activity.
Pls help me, its so frustrating, waste so many hours for just a toolbar, which already exists..
Try adding toolbar in you activity :
mTopToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(mTopToolbar);
Get the Activity that owns the fragment (Fragment.getActivity()) and set its ActionBar property.
Then juse use the same setDisplayHomeAsUpEnabled method you mentioned to begin with on the ActionBar after setting your toolbar as the ActionBar to get the back / up button.
sample to access it from fragment :
((AppCompatActivity)getActivity()).getSupportActionBar().setSubtitle();
Hope it helps.
As simple as this.
Toolbar toolbar = ((ChoosingActivity)getActivity()).findViewById(R.id.toolbar);
Now do whatever you want to do man ;).
It's probably because your Toolbar is covered by everything else in DrawerLayout. Try swapping LinearLayout and DrawerLayout, so that the vertical LinearLayout is your root layout, something like this:
<LinearLayout 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"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimary"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawerChooser"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/new_gradients"
android:fitsSystemWindows="true"
tools:context=".ChoosingActivity">
<FrameLayout
android:id="#+id/fragment_container_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.v4.widget.DrawerLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/header"
app:menu="#menu/drawer_menu">
</android.support.design.widget.NavigationView>
</LinearLayout>
Something approximately like that, the key is that your Toolbar has to be outside your DrawerLayout.

FloatingActionButton in Activity with multiple Fragments?

I have an issue that I can't seem to solve.
I have an activity with a list fragment (landscape and portrait) and an addItem fragment.
There is a FloatingActionButton on the Activity, but I can't seem to figure out how to set up its onClickListener.
The getViewById always returns null so the setOnClickListener has no object to call from. Why is this and how do I fix it?
Am I doing multiple fragments wrong and this is my problem?
Note: I left out the landscape fragment/layout for brevity's sake. It's the same as the portrait with a different id.
MainActivity.java
package tlw.app;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ArrayList<String> activeFragments = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
setContentView(R.layout.fragment_list);
FragmentManager fManager = getFragmentManager();
FragmentTransaction fTrans = fManager.beginTransaction();
Configuration configInfo = getResources().getConfiguration();
activeFragments.clear();
if(configInfo.orientation == Configuration.ORIENTATION_LANDSCAPE){
ListFragmentLand fragmentListLand = new ListFragmentLand();
fTrans.replace(R.id.main_container, fragmentListLand);
activeFragments.add("list_land");
} else {
ListFragment fragmentListPort = new ListFragment();
fTrans.replace(R.id.main_container, fragmentListPort);
activeFragments.add("list_port");
}
fTrans.commit();
if (activeFragments.contains("list_port") || activeFragments.contains("list_land")){
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FragmentManager fManager = getFragmentManager();
FragmentTransaction fTrans = fManager.beginTransaction();
activeFragments.clear();
ItemAddFragment fragmentAdd = new ItemAddFragment();
fTrans.replace(R.id.main_container, fragmentAdd);
activeFragments.add("add");
fTrans.commit();
}
});
}
}
}
activity_main.xml
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
app:srcCompat="#android:drawable/ic_dialog_email" />
<FrameLayout
android:id="#+id/main_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</android.support.design.widget.CoordinatorLayout>
ListFragment.xml
package tlw.app;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class ListFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_list, container, false);
}
}
fragment_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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/fragment_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="tlw.app.MainActivity"
tools:showIn="#layout/activity_main"
android:orientation="vertical">
<TextView
android:id="#+id/text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="List Portrait"/>
</LinearLayout>
ItemAddFragment.java
package tlw.app;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class ItemAddFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_add, container, false);
}
}
fragment_add.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment_add"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/textView_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name:"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/editText_name"
/>
</LinearLayout>
</LinearLayout>
Please change this portion of the code in the MainActivity
FROM
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
setContentView(R.layout.fragment_list);
TO
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Mistakes::
--Passing wrong xml instance::
--Trying to fetch the toolbar before the xml was actually set..
Please tell if more assistance needed
setContentView(R.layout.fragment_list);
This sets the layout used for your activity which does not have a FAB. Change this line to
setContentView(R.layout.activity_main);
In general, whenever findViewById() returns null, you need to be sure that the correct XML is loaded and that it contains the id you are trying to find.

Android Fragment not inflating after transaction

I've been trying to inflate a simple contentFragment after clicking on the tab from my navigation drawer. Here is my CentralView class that contains the attempt to inflate the Fragment
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.widget.Toast;
#SuppressWarnings("deprecation")
public class CentralView extends AppCompatActivity {
private Toolbar toolbar;
private NavigationView navigationView;
private DrawerLayout drawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_central_view);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
navigationView = (NavigationView) findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
//Checking if the item is in checked state or not, if not make it in checked state
if(menuItem.isChecked()) menuItem.setChecked(false);
else menuItem.setChecked(true);
//Closing drawer on item click
drawerLayout.closeDrawers();
//Check to see which item was being clicked and perform appropriate action
switch (menuItem.getItemId()){
//Replacing the main content with ContentFragment Which is our Inbox View;
case R.id.home:
Toast.makeText(getApplicationContext(),"Inbox Selected",Toast.LENGTH_SHORT).show();
ContentFragment fragment = new ContentFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame,fragment);
fragmentTransaction.commit();
return true;
And here is my ContentFragment class
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Admin on 04-06-2015.
*/
public class ContentFragment extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_content_fragment,container,false);
return v;
}
}
I've searched StackOverflow and while people have had similar issues, none of the fixes worked for me. Apologies if it's out there. Here is the XML for my content Fragment as well
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="wrap_content"
android:layout_height="wrap_content"
android:text="INBOX"
android:padding="8dp"
android:textColor="#fff"
android:background="#color/colorPrimary"
android:textSize="28sp"
android:id="#+id/textView"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
edit: adding activity_central_view.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 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:id="#+id/drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".CentralView">
<LinearLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical"
>
<include
android:id="#+id/toolbar"
layout="#layout/tool_bar"/>
<FrameLayout
android:id="#+id/frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="#+id/navigation_view"
android:layout_height="match_parent"
android:layout_width="wrap_content"
android:layout_gravity="start"
app:headerLayout="#layout/header"
app:menu="#menu/drawer"/>
</android.support.v4.widget.DrawerLayout>
I suspect your tool_bar layout might be having a height of match_parent.
Could you please share tool_bar file?

fragment to activity Backstack returns blank view

I had Created a Home activity which includes Tablayout and Navigation Drawer onclick with fragment. I had included fragmentTransaction.addToBackStack(null).commit(); with the fragment transaction code to go back to previous Activity.
My Desired requirement was From Activity with tablayout-->NavigationDrawer-->Fragment1--> On BackButtonPress-->MainActivity with tablayout.
But,Now i am able to move to Fragment1,and when return to MainActivity,the view becomes filled with white(if i use mainLayout.removeAllViews(); and if wont use mainLayout.removeAllViews(); ,then the fragment is overlapping with the MainActivity)
1.My mainactivty
2.fragment
3.when i return to mainactivty
Now i cant see tablayout in my MainActivity.
Can anyone please help me.
mainactivity_layout.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"
android:paddingBottom="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".HomeActivity"
android:id="#+id/mainlayout"
tools:showIn="#layout/app_bar_home">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/rel">
<RelativeLayout
android:id="#+id/main_layout1"
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=".MainActivity">
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
<android.support.v4.view.ViewPager
android:id="#+id/pager1"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_below="#id/tab_layout1"/>
</RelativeLayout>
</RelativeLayout>
</RelativeLayout>
MainActivity.java
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.RelativeLayout;
import java.io.File;
import java.util.ArrayList;
public class HomeActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
TabLayout tabLayout1 = (TabLayout) findViewById(R.id.tab_layout1);
tabLayout1.addTab(tabLayout1.newTab().setIcon(R.drawable.tab_ic_home));
tabLayout1.addTab(tabLayout1.newTab().setIcon(R.drawable.tab_ic_map));
tabLayout1.addTab(tabLayout1.newTab().setIcon(R.drawable.tab_ic_login));
tabLayout1.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager1 = (ViewPager) findViewById(R.id.pager1);
final PagerAdapter1 adapter = new PagerAdapter1
(getSupportFragmentManager(), tabLayout1.getTabCount());
viewPager1.setAdapter(adapter);
viewPager1.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout1));
tabLayout1.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager1.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
// Handle navigation view item clicks here.
int id = item.getItemId();
RelativeLayout mainLayout=(RelativeLayout)findViewById(R.id.main_content);
if (id == R.id.nav_login) {
LoginFragment fragment = new LoginFragment();
// mainLayout.removeAllViews();
fragmentTransaction.replace(R.id.mainlayout, fragment);
fragmentTransaction.addToBackStack(null).commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Fragment.java
import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class ContactFragment extends Fragment implements OnMapReadyCallback {
private GoogleMap mMap;
Button call;
public ContactFragment() {
// Required empty public constructor
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_contact,container,false);
call = (Button) v.findViewById(R.id.button5);
call.setOnClickListener(new View.OnClickListener() {
#SuppressLint("NewApi")
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_DIAL);
i.setData(Uri.parse("tel:7034409615"));
startActivity(i);
}
});
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
return v;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(9.2700, 76.7800);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Pathanamthitta"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
}
As I suggested in the comments, in order to figure out the problem with displaying of fragments you can try to view what kind of fragments are being added into back stack as follows
Log.d("FragmentList",getSupportFragmentManager().getFragments().toString();
You can put it inside onBackPressed() ,onNavigationItemSelected()
According to your feedback it was helpful for you and you figured out the problem.
Also there are some layout design issues:
Your current approach is to adding fragment into relative layout. I believe it leads to some problems with view. The recommended approach is to add fragments into FrameLayout as described in docs
Also you may want to move everything outside view used for fragments
I have rewritten your layout following recommended guidelines in the docs. P.S I haven't tested how it displayed.. you may have to tweak some layout params.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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">
<!--
Layout for fragments
-->
<FrameLayout
android:id="#+id/mainlayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/app_bar_home">
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/rel">
<RelativeLayout
android:id="#+id/main_layout1"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" android:orientation="horizontal"/>
<android.support.v4.view.ViewPager
android:id="#+id/pager1"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_below="#id/tab_layout1"/>
</RelativeLayout>
</RelativeLayout>
</LinearLayout>
Also You defined multiple activities in your layout like tools:context=".MainActivity" and tools:context=".HomeActivity" I guess it's just unedited copy paste, but may lead some issues as well.
Hope you find it useful :)
In your MainActivity.java add this:
protected OnBackPressedListener onBackPressedListener;
public interface OnBackPressedListener {
void doBack();
}
public void setOnBackPressedListener(OnBackPressedListener onBackPressedListener) {
this.onBackPressedListener = onBackPressedListener;
}
#Override
public void onBackPressed() {
if (onBackPressedListener != null)
onBackPressedListener.doBack();
else
super.onBackPressed();
}
Than in Fragment.java implements class like this:
implements MainActivity.OnBackPressedListener
And implements method:
#Override
public void doBack() {
Intent yourMainActivity = new Intent(getActivity(), MainActivity.class);
startActivity(yourMainActivity);
}
Rubin Nellikunnathu. I had the same issue. Make replacing of your NavigationView fragments in FrameLayout, not RelativeLayout. So you always would have TabLayout and ViewPager loaded.
Place it in mainactivity_layout.xml or in app_bar_home.xml (I do not see your full code, so you try these combinations).
mainactivity_layout.xml
<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"
android:paddingBottom="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".HomeActivity"
android:id="#+id/mainlayout"
tools:showIn="#layout/app_bar_home">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/rel">
<RelativeLayout
android:id="#+id/main_layout1"
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=".MainActivity">
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
<android.support.v4.view.ViewPager
android:id="#+id/pager1"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_below="#id/tab_layout1"/>
</RelativeLayout>
</RelativeLayout>
// Replace NavigationView fragments in this FrameLayout
<FrameLayout
android:id="#+id/flForReplace"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".FrameLayout" />
</RelativeLayout>
and your code should be
fragmentTransaction.replace(R.id.flForReplace, fragment);
also replace fragmentTransaction.addToBackStack(null).commit(); with fragmentTransaction.commit(); as ρяσѕρєя K suggested.

Categories

Resources