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?
Related
I have a TabLayout on a activity and when user clicks on any tab then a fragment is loaded. One of those fragments contains a NavigationView running inside a DrawerLayout. Now the problem is I have to implement MVVM for the whole app and so for the fragments too, I have done this for Activities but I am having trouble while implementing this for Fragments and how to deal with ItemSelected with MVVM and what to bind and how? I am unable to find a proper working sample of the same. Here's the code:
MoreFragment.java:
package com.abc.Fragments;
import android.arch.lifecycle.ViewModel;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Context;
import android.net.Uri;
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.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.abc.MainActivity;
import com.abc.MoreFragmentViewModel;
import com.abc.R;
public class MoreFragment extends Fragment {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ViewModel viewModel;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
viewModel = ViewModelProviders.of(this).get(MoreFragmentViewModel.class);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View fragView = inflater.inflate(R.layout.fragment_more, container, false);
return fragView;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mDrawerLayout = getView().findViewById(R.id.drawer_layout);
mDrawerLayout.openDrawer(Gravity.END);
}
}
fragment_more.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"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white">
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="end"
android:background="#color/grey"
app:navigationItemSelectedListener="#{()-> viewModel.onMyItemSelected()}"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>
MoreFragmentViewModel.java:
package com.abc;
import android.arch.lifecycle.ViewModel;
import android.databinding.BaseObservable;
public class MoreFragmentViewModel extends ViewModel {
public void onMyItemSelected(){
System.out.print("Item Clicked");
}
}
Please do any possible help.
Use:
DataBindingUtil.inflate(inflater, layoutId(), container, false)
To inflate your layout.
And don't forget to add:
<data>
<variable
name="model"
type="MoreFragmentViewModel"/>
</data>
To your fragment layout.
First let me clarify that i have found a few questions similar to this question, but none worked for me.
So i have one activity (MainActivity.java), which has a bottom navigation tab, each tab has its own fragment, the third fragment is named 'ServiceFragment.java' (also the third tab in Bottom navigation).
Classes:
ServiceFragment.java
package in.ikleen.ikleenservices;
import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class ServiceFragment extends Fragment {
Context context;
public ServiceFragment() {
// Required empty public constructor
}
#Override
public void onAttach (Context context){
super.onAttach(context);
this.context = context;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_service, container, false);
ViewPager viewPager = rootView.findViewById(R.id.service_view_pager);
viewPager.setOffscreenPageLimit(3);
TabLayout tabLayout = rootView.findViewById(R.id.service_tab_layout);
ServiceFragmentPageAdapter pageAdapter = new ServiceFragmentPageAdapter(context, getChildFragmentManager());
viewPager.setAdapter(pageAdapter);
tabLayout.setupWithViewPager(viewPager);
return rootView;
}
}
ServiceFragmentPageAdapter.java
package in.ikleen.ikleenservices;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class ServiceFragmentPageAdapter extends FragmentPagerAdapter {
private Context mContext;
Fragment zero, first, second;
public ServiceFragmentPageAdapter (Context context, FragmentManager fm){
super(fm);
mContext = context;
zero = new WashDryServiceFragment();
first = new WashDryIronServiceFragment();
second = new AdditionalProductsServiceFragment();
}
#Override
public Fragment getItem(int position){
switch (position){
case 0:
return zero;
case 1:
return first;
case 2:
return second;
default:
return zero;
}
}
#Override
public int getCount(){
return 3;
}
#Override
public CharSequence getPageTitle(int position){
switch (position){
case 0:
return mContext.getString(R.string.wash_dry);
case 1:
return mContext.getString(R.string.wash_dry_iron);
case 2:
return mContext.getString(R.string.additional_products);
default:
return mContext.getString(R.string.wash_dry);
}
}
}
WashDryServiceFragment.java (the first tab of viewpager tablayout, also the one bearing the problem)
package in.ikleen.ikleenservices;
import android.annotation.TargetApi;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.app.Fragment;
import android.support.v4.widget.NestedScrollView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toolbar;
import java.lang.annotation.Target;
import java.util.ArrayList;
import java.util.List;
public class WashDryServiceFragment extends Fragment {
public WashDryServiceFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_wash_dry_service, container, false);
ListView listView = (ListView) rootView.findViewById(R.id.listViewWashDryService);
ArrayList<String> stringList = new ArrayList<>();
for(int i=0; i<20; i++) {
stringList.add("Hello");
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, stringList);
listView.setAdapter(adapter);
//TESTED BELOW CODE BUT CANNOT EVEN SCROLL A LITTLE BIT SO COMMENTED IT
//Toolbar toolbar = (Toolbar) rootView.findViewById(R.id.toolbar1);
//NestedScrollView nestedScrollView = (NestedScrollView) rootView.findViewById(R.id.nestedScroll);
//CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) nestedScrollView.getLayoutParams();
//params.setBehavior(new ConstrainedScrollBehavior());
return rootView;
}
}
Layouts:
fragment_service.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"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="in.ikleen.ikleenservices.ServiceFragment">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.TabLayout
android:id="#+id/service_tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabTextAppearance="#style/Base.TextAppearance.AppCompat.Small"
app:tabMode="fixed"/>
<android.support.v4.view.ViewPager
android:id="#+id/service_view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
</FrameLayout>
fragment_wash_dry_service.xml (THE PROBLEM LIES HERE)
<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"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="in.ikleen.ikleenservices.WashDryServiceFragment">
<android.support.design.widget.CoordinatorLayout
android:id="#+id/coordinatorlayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:id="#+id/appBarLayout"
android:layout_width="match_parent"
android:layout_height="150dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.design.widget.CollapsingToolbarLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal"
app:layout_collapseMode="parallax"
android:scaleType="centerInside"
app:layout_collapseParallaxMultiplier="0.5"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
android:src="#mipmap/ld_00"/>
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.widget.NestedScrollView
android:id="#+id/nestedScroll"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:fillViewport="true"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:layout_gravity="fill_vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:orientation="vertical">
<ListView
android:id="#+id/listViewWashDryService"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/appBarLayout"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="JUST FOR TESTS"
android:textAppearance="#style/TextAppearance.AppCompat.Large"/>
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>
</FrameLayout>
Thanks
The problem in this case was: (p.s. i am stupid)
listview cannot scroll inside nestedscrollview, so as soon as the collapsingtoolbar collapsed, there was no need for the nestedscrollview to scroll more as it already filled the parent and listview could not scroll anyways. (i know, dumb explanation)
Solution:
1: either remove listview inside the nestedscrollview
OR
2: add this attribute android:nestedScrollingEnabled="true" inside nestedscrollview (not tested, but should work)
Since a few days ago I decided to program for Android and buy a book about that. There are several examples and I have achieved them satisfactorily but at the moment of programming the navigation drawer and running it on my cell phone it appears that it closed unfortunately. In the console of Android Studio does not appear any error and I was reviewing codes, example, etc and I have not been able to solve the problem.
Here you can see part of the application code to create and initialize the toolbar and the drawer layout
package com.example.luisenrique.clase_aplicacion;
import android.content.SharedPreferences;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.example.luisenrique.clase_aplicacion.fragments.DetalleFragment;
import com.example.luisenrique.clase_aplicacion.fragments.SelectorFragment;
import static android.R.id.toggle;
import static com.example.luisenrique.clase_aplicacion.R.id.appBarLayout;
import static com.example.luisenrique.clase_aplicacion.R.id.drawer_layout;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private AdaptadorLibrosFiltro adaptador;
private AppBarLayout appBarLayout;
private TabLayout tabs;
private DrawerLayout drawer;
private ActionBarDrawerToggle toggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if((findViewById(R.id.contenedor_pequeno)!=null) && (getSupportFragmentManager().findFragmentById(R.id.contenedor_pequeno)==null)){
SelectorFragment primerFragment=new SelectorFragment();
getSupportFragmentManager().beginTransaction().add(R.id.contenedor_pequeno,primerFragment).commit();
}
adaptador=((Aplicacion)getApplicationContext()).getAdaptador();
appBarLayout=(AppBarLayout)findViewById(R.id.appBarLayout);
//Pestañas
TabLayout tabs=(TabLayout)findViewById(R.id.tabs);
tabs.addTab(tabs.newTab().setText("Todos"));
tabs.addTab(tabs.newTab().setText("Nuevos"));
tabs.addTab(tabs.newTab().setText("Leidos"));
tabs.setTabMode(TabLayout.MODE_SCROLLABLE);
tabs.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener(){
#Override
public void onTabSelected(TabLayout.Tab tab){
switch (tab.getPosition()){
case 0: //Todos
adaptador.setNovedad(false);
adaptador.setLeido(false);
break;
case 1: //Nuevos
adaptador.setNovedad(true);
adaptador.setLeido(false);
break;
case 2: //Leidos
adaptador.setNovedad(false);
adaptador.setLeido(true);
break;
}
adaptador.notifyDataSetChanged();
}
#Override
public void onTabUnselected(TabLayout.Tab tab){}
#Override
public void onTabReselected(TabLayout.Tab tab){}
});
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.drawer_open,R.string.drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView=(NavigationView)findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item){
int id=item.getItemId();
if(id==R.id.nav_todos){
adaptador.setGenero("");
adaptador.notifyDataSetChanged();
}
else if(id==R.id.nav_epico){
adaptador.setGenero(Libro.G_EPICO);
adaptador.notifyDataSetChanged();
}
else if(id==R.id.nav_XIX){
adaptador.setGenero(Libro.G_S_XIX);
adaptador.notifyDataSetChanged();
}
else if(id==R.id.nav_suspense){
adaptador.setGenero(Libro.G_SUSPENSE);
adaptador.notifyDataSetChanged();
}
DrawerLayout drawer=(DrawerLayout)findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onBackPressed(){
DrawerLayout drawer=(DrawerLayout)findViewById(R.id.drawer_layout);
if(drawer.isDrawerOpen(GravityCompat.START)){
drawer.closeDrawer(GravityCompat.START);
}
else{
super.onBackPressed();
}
}
}
<!--activity main.xml-->
the main activity is where the main view will be shown and it will be linked to app_bar_main_xml where the other components are located that have no relation to the navigation drawer and work correctly and therefore I will not put the code.
<?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"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<!--El contenido de la actividad-->
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<!--El contenido del navigation drawer-->
<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>
<!--nav header-->
<?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="160dp"
android:background="#color/colorAccent"
android:gravity="bottom"
android:orientation="vertical"
android:paddingBottom="16dp"
android:paddingLeft="?attr/listPreferredItemPaddingLeft"
android:paddingRight="?attr/listPreferredItemPaddingRight"
android:paddingTop="16dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark">
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="16dp"
android:src="#android:drawable/sym_def_app_icon"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="16dp"
android:text="Audiolibros"
android:textAppearance="#style/TextAppearance.AppCompat.Body1"/>
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="http://www.androidcurso.com"/>
</LinearLayout>
<!--menu activity_main_drawer.xml-->
in the menu you will see how the navigation drawer will be sectioned. what items will be available and how they will be grouped.
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item android:id="#+id/nav_todos"
android:icon="#android:drawable/ic_menu_gallery"
android:title="Todos los generos"/>
<item android:id="#+id/nav_epico"
android:icon="#android:drawable/ic_menu_gallery"
android:title="Poema épico"/>
<item android:id="#+id/nav_XIX"
android:icon="#android:drawable/ic_menu_gallery"
android:title="Literatura siglo XIX"/>
<item android:id="#+id/nav_suspense"
android:icon="#android:drawable/ic_menu_gallery"
android:title="Suspense"/>
</group>
<item android:title="Acciones adicionales">
<menu>
<item android:id="#+id/nav_preferencias"
android:icon="#android:drawable/ic_menu_manage"
android:title="Preferencias"/>
<item android:id="#+id/nav_compartir"
android:icon="#android:drawable/ic_menu_share"
android:title="Compartir"/>
</menu>
</item>
</menu>
It is to call the texts that are required in other classes, there are only two that are called opening and closing.
<!--Strings-->
<resources>
<string name="app_name">Clase_Aplicacion</string>
<string name="drawer_open">navigation drawer abierto</string>
<string name="drawer_close">navigation drawer cerrado</string>
</resources>
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 ;
Pretty new to android development, I need to know how I can change the size of my ListView in my fragment pragmatically to cover the entire screen? match_parent, fill_parent didn't work.
I have hard coded values of 500dp
Here is my fragment
<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=".MainActivity">
<ListView
android:id="#android:id/list"
android:layout_width="500dp"
android:layout_height="500dp"
android:divider="#null"
android:dividerHeight="0dp"
android:layout_marginTop="0dp">
</ListView>
</RelativeLayout>
and here is JAVA my fragment code:
import android.app.ListFragment;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import java.util.List;
public class MyFragment extends ListFragment {
List<data> flowers = new datadata().getdatas();
public MyFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dataArrayAdapter adapter = new dataArrayAdapter(getActivity(),
R.layout.data_listitem,
flowers);
setListAdapter(adapter);
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.my_fragment, container, false);
return rootView;
}
}
here is my main Activity class
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/myContainer"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scrollbarStyle="insideOverlay"
android:scrollbars="none"
android:fadeScrollbars="true"
android:fitsSystemWindows="true"
android:layout_gravity="top"
>
</ScrollView >
and this is my main activity java code:
package mshirvan.example.com.netplex;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.Intent;
import android.media.Image;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import android.view.View.OnClickListener;
import data.row1;
public class MainActivity extends Activity {
public static float screenx = 0;
public static float screeny = 0;
public static int screenpixelx = 0;
public static int screenpixely = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ScreenUtility utility = new ScreenUtility(this);
screenx = utility.getWidth();
screeny = utility.getHeight();
screenpixelx = utility.getPixelWidth();
screenpixely = utility.getPixelHeight();
MyFragment frag = new MyFragment();
getFragmentManager().beginTransaction()
.add(R.id.myContainer, frag)
.commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, 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();
if (id == R.id.action_settings) {
ScreenUtility utility = new ScreenUtility(this);
String output = "Width: " + utility.getWidth() + ", " +
"Height: " + utility.getHeight();
return true;
}
return super.onOptionsItemSelected(item);
}
}
Add the following to your fragment RelativeLayout. This should be as follows:
android:layout_width="match_parent"
android:layout_height="500dp"
For example the map layout fragment should be as follows :
<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="500dp"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity"
>
<com.google.android.gms.maps.MapView
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true" />
</RelativeLayout>
Then add this fragment layout in the main layout.
put these in your listview too:
android:layout_width="match_parent"
android:layout_height="match_parent"
or you can change the layoutparameters to match_parent in yout fragment
that contains the listview.
you have to set the fragment container height to match parent not ListView. in your case ,ListView will fill it's parent height. ListView's parent is RelativeLayout and the RelativeLayout height is matchParent that means , RelativeLayout will also fill it's container and it's container is your fragment place holder that defined in your activity's layout file. you have to set that container's height to matchParent.
I think the problem is that you are trying to add fragment to ScrollView. use FrameLayout with android:layout_height=match_parent for fragment's container and if you have to add multiple fragments, then define multiple FrameLayouts in your activity's layout or add them dynamically.