PreferenceFragmentCompat inside (child of) Fragment not dispatching first touch event - android

i am creating setting of my app and am using fragments i made PreferenceFragmentCompat screen and in my parent Fragment i load it on setting click but when i first click on any preference its does not respond to my first touch but after some short time it works normal or when i scroll up or down fast and click on any preference right after it it does not respond to my touch event can someone help please?
public class SettingsParent extends Fragment {
Toolbar toolbar;
private HomeActivity homeActivity;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable final ViewGroup container, #Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
homeActivity = ((HomeActivity) getActivity());
View rootView = inflater.inflate(R.layout.settings_parent, container, false);
toolbar = (Toolbar) rootView.findViewById(R.id.toolbar);
setTitle(getString(R.string.settings));
setFragment(new SettingsFragment());
homeActivity.setSupportActionBar(toolbar);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
homeActivity.onBackPressed();
}
});
rootView.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
Log.e("SettingTouch","parent");
return true;
}
});
android.support.v7.app.ActionBar actionBar = homeActivity.getSupportActionBar();
assert actionBar != null;
actionBar.setDisplayHomeAsUpEnabled(true);
return rootView;
}
private void setTitle(String string) {
toolbar.setTitle(string);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
//inflater.inflate(R.menu.browser_options_menu, menu);
menu.setGroupVisible(R.id.grp, false);
super.onCreateOptionsMenu(menu, inflater);
}
void setFragment(Fragment newFragment){
FragmentManager fragmentManager = getChildFragmentManager();
fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
android.support.v4.app.FragmentTransaction ft = getChildFragmentManager().beginTransaction();
ft.replace(R.id.childF, newFragment, "detailFragment");
ft.commit();
}
}
this is xml of parentFragment.
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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.support.design.widget.AppBarLayout
android:id="#+id/main.appbar"
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"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/child_fragment" />
</android.support.design.widget.CoordinatorLayout>
and this is my child PreferenceFragmentCompat.
public class SettingsFragment extends PreferenceFragmentCompat implements HomeActivity.Authentication, Preference.OnPreferenceClickListener, SharedPreferences.OnSharedPreferenceChangeListener, ConfirmAlertDialog.OnDialogClickInterface {
#Override
public boolean onPreferenceClick(final Preference preference) {
final String key = preference.getKey();
switch (key) {
case "remove_ads":
homeActivity.purchaseRemoveAds();
break;
case "hide_icon":
try {
homeActivity.loadFragment(new HideOptiosTutorial(), getParentFragment().getFragmentManager().beginTransaction());
} catch (Exception e) {
e.printStackTrace();
}
break;
case "key_share_app_link":
shareAppFile();
break;
case "move_to_sdcard":
showMovetoSdDialog();
break;
case "button_internal":
showMovetoInternalDialog();
break;
case "back_up_sdcard":
if (isSDCardUnmounted()) {
showSDCardMountError();
} else {
globalPasswords = getBackupPasswords();
if (!FileUtilis.isSafAllowed(getActivity())) {
showSDCardNotAllowedDialog(983);
//
return false;
}
if (globalPasswords.size() == 0) {
showNoBackupFoundMsg();
} else {
showDialogToBackupFromSDCard();
}
}
break;
case "change_password":
showChangePinDialog();
break;
case "key_rate_us":
rateApplication();
break;
case "app_link":
SavedAlbumsFragment.showAppLockLink(getActivity());
break;
case "view_intruders":
startActivity(new Intent(homeActivity, ViewIntruders.class));
break;
case "theme":
showSelectTehmeDialog();
break;
case "enter_email":
showChangeEmailDialog();
break;
}
return false;
}
#Override
public void onCreatePreferences(Bundle bundle, String s) {
addPreferencesFromResource(R.xml.pref_headers);
Log.e("Mateen","onCreatePreferences");
homeActivity = ((HomeActivity) getActivity());
homeActivity.addAuthenticationListner(this);
localDatabase = LocalDatabase.getInstance(getActivity());
localPreferences = new LocalPreferences(getActivity());
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
LocalBroadcastManager.getInstance(homeActivity).registerReceiver(broadcastReceiver,new IntentFilter("Remove_Is_Purchased"));
removeAdsPref=findPreference("remove_ads");
mCategory = (PreferenceCategory)findPreference("cat_remove_ads");
if (localPreferences.IsRemovedAdsPurchased())
{
mCategory.removePreference(removeAdsPref);
getPreferenceScreen().removePreference(mCategory);
}
else
{
removeAdsPref.setOnPreferenceClickListener(this);
}
findPreference("move_to_sdcard").setOnPreferenceClickListener(this);
findPreference("view_intruders").setOnPreferenceClickListener(this);
findPreference("button_internal").setOnPreferenceClickListener(this);
findPreference("back_up_sdcard").setOnPreferenceClickListener(this);
findPreference("change_password").setOnPreferenceClickListener(this);
findPreference("key_rate_us").setOnPreferenceClickListener(this);
findPreference("app_link").setOnPreferenceClickListener(this);
findPreference("hide_icon").setOnPreferenceClickListener(this);
findPreference("key_share_app_link").setOnPreferenceClickListener(this);
findPreference("listPref_wrong_tries").setOnPreferenceClickListener(this);
findPreference("theme").setOnPreferenceClickListener(this);
findPreference("enter_email").setOnPreferenceClickListener(this);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
findPreference("key_cam_short").setVisible(false);
findPreference("key_vid_short").setVisible(false);
}
if (!PreferenceManager.getDefaultSharedPreferences(homeActivity).getBoolean("key_intruder_detection",false))
{
findPreference("listPref_wrong_tries").setEnabled(false);
}
if (!Reprint.isHardwarePresent()) {
findPreference("key_fingerprint").setEnabled(false);
}
if (!FileUtilis.isSdcardPresent(getActivity())) {
findPreference("move_to_sdcard").setEnabled(false);
findPreference("button_internal").setEnabled(false);
findPreference("back_up_sdcard").setEnabled(false);
// findPreference("change_password").setEnabled(false);
findPreference("always_save_to_sdcard").setEnabled(false);
}
//add xml
}
but if i directly load child Fragment(SettingsParent) from my activity it works perfect without action bar.
can someone help or with better approach but i don't want to use activity i need fragment with action bar.

i solved my problem by removing
app:layout_scrollFlags="scroll|enterAlways"
from:
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
now it is listening to my every damn touch :D
Happy coding

Related

Call to Fragment clears app view on startActivity()

I am new to Android development and have added an additional item to a Navigation menu which successfully opens an external browser window but clears the app screen (except for the navigation menu) when startActivity in onActivityCreated is performed.
I am not making any more progress despite working on this for several days so I am asking for help now. Perhaps this is a simple question for someone with more experience. I have spent a week looking at all the other answers in SO, YouTube and Google Developer Courses trying to solve this so I am asking for help now.
WebsiteFragment.java
public class WebsiteFragment extends Fragment {
View myFragment;
RecyclerView websiteList;
LinearLayoutManager layoutManager;
private static final String COMMON_TAG="CombinedLifeCycle";
private static final String ACTIVITY_NAME =WebsiteFragment.class.getSimpleName();
private static final String TAG=ACTIVITY_NAME;
public static WebsiteFragment newInstance() {
WebsiteFragment websiteFragment = new WebsiteFragment();
return websiteFragment;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
//Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_website, container, false);
Log.i(TAG,ACTIVITY_NAME+" onCreateView");
websiteList = (RecyclerView)view.findViewById(R.id.websiteList);
layoutManager = new LinearLayoutManager(getActivity());
websiteList.setHasFixedSize(true);
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse("https://english-alps.com"));
// App Window is cleared??
getActivity().startActivity(i);
Log.i(TAG,ACTIVITY_NAME+" onActivityCreated");
}
}
fragment_webiste.xml
<?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=".WebsiteFragment">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/websiteList"
android:layout_width="match_parent"
android:layout_height="match_parent">
</androidx.recyclerview.widget.RecyclerView>
</FrameLayout>
Edit 21-08-2018
Added the following code to try and save Fragment state but it generates the error:
java.lang.NullPointerException: Attempt to read from field 'int androidx.fragment.app.Fragment.mIndex' on a null object referen.
I am having trouble with the parameters to getFragmentManager. How should the variables to getFragmentManager be initialized?
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState!=null){
Log.i(TAG,ACTIVITY_NAME+" calling onSaveInstanceState");
onSaveInstanceState(savedInstanceState);
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
getFragmentManager().putFragment(outState,TAG,myFragment);
Log.i(TAG,ACTIVITY_NAME+" onSaveInstanceState");
}
Edit#2 21-08-2018
Home.Java which adds WebsiteFragment to the Activity
public class Home extends AppCompatActivity {
BottomNavigationView bottomNavigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
bottomNavigationView = (BottomNavigationView) findViewById(R.id.navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment selectedFragment = null;
switch (menuItem.getItemId()) {
case R.id.action_category:
selectedFragment = CategoryFragment.newInstance();
break;
case R.id.action_ranking:
selectedFragment = RankingFragment.newInstance();
break;
case R.id.action_website:
selectedFragment = WebsiteFragment.newInstance();
break;
}
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_layout, selectedFragment);
transaction.addToBackStack(String.valueOf(R.id.frame_layout)); /* 21.08.2018 */
transaction.commit();
return true;
}
});
setDefaultKeyMode();
}
}
Edit #3 21-08-2018 activity_home.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Home">
<FrameLayout
android:id="#+id/frame_layout"
android:animateLayoutChanges="true"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/navigation"></FrameLayout>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#color/colorPrimary"
app:itemIconTint="#drawable/nav_item_color_state"
app:itemTextColor="#drawable/nav_item_color_state"
app:menu="#menu/bottom_menu"
/>
</RelativeLayout>

Fullscreen Dialog Fragment not showing correctly

I've got two problems:
In my app I have an activity with the appbar and a recycler view.
When i click an option of the floating action menu it displays a Fullscreen Dialogfragment but for some reason the dialog is not showing correctly (not totaly fullscreen).
Here is the result
dialogfragment
Also when I click the close button of the Dialog it closes not only the dialog, but the activity as well, and goes to the previous activity.
What should I do. I am beginning Android.
also I want to establish a margin for the cardview (left and right)
Here is my code
Result_contract.java
public class Result_contract extends AppCompatActivity implements
FragmentActions{
String TAG="Result_contract";
private boolean first_time= true;
private List<Contract>lista_contratos;
private FloatingActionsMenu fabm;
private RecyclerView recycler;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager lManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result_contract);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Contratos");//Set title
getSupportActionBar().setDisplayHomeAsUpEnabled(true);//Enable Back button
fabm= (FloatingActionsMenu)findViewById(R.id.menu_fab);
View fab_buscar = findViewById(R.id.accion_buscar);
fab_buscar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showSearchDialog();
}
});
View fab_formulario = findViewById(R.id.accion_formulario);
fab_formulario.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showDetailsDialog(0);
}
});
recycler = (RecyclerView) findViewById(R.id.reciclador);
recycler.setHasFixedSize(true);
lManager = new LinearLayoutManager(this);
recycler.setLayoutManager(lManager);
//todo REMOVER ESTO
//SearchContractTask buscar = new SearchContractTask(Contract_query_instance.getInstance().getContractQuery());
//buscar.execute();
SearchContractTask buscar = new SearchContractTask(null);
buscar.execute();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// app icon in action bar clicked; goto parent activity.
this.finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void showDetailsDialog(int position) {
fabm.collapse();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
Fragment fragment=new Dialog_contract();
Bundle args=new Bundle();
args.putInt("position",position);
fragment.setArguments(args);
transaction.add(android.R.id.content, fragment,"dialog_contract").addToBackStack(null).commit();
}
#Override
public void showSearchDialog() {
fabm.collapse();
}
#Override
public void load_data() {
}
public class SearchContractTask extends AsyncTask<Void, Void, Void> {
Connection cnx;
Models models;
Contract_query query;
public SearchContractTask(Contract_query query) {
super();
cnx = Connection.getConnection();
models= Models.getInstance();
this.query=query;
}
#Override
protected Void doInBackground(Void... voids) {
lista_contratos=Contract_list.getInstance().getList_contract();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (lista_contratos!=null) {
adapter = new Contract_adapter(lista_contratos);
recycler.setAdapter(adapter);
}
else {
//TODO MOSTRAR UN MENSAJE DE QUE NO EXISTEN FILAS EN LA CONSULTA
}
}
#Override
protected void onCancelled() {
}
}
#Override public boolean dispatchTouchEvent(MotionEvent event){
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (fabm.isExpanded()) {
Rect outRect = new Rect();
fabm.getGlobalVisibleRect(outRect);
if(!outRect.contains((int)event.getRawX(), (int)event.getRawY()))
fabm.collapse();
}
}
return super.dispatchTouchEvent(event);
}
#Override
public void onBackPressed() {
if (fabm.isExpanded()) {
fabm.collapse();
}
else{
finish();
}
//super.onBackPressed();
}
}
activity_reult_contract.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:fitsSystemWindows="true"
tools:context="com.example.ernesto.apptranscargo.Result_contract">
<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>
<include layout="#layout/content_result_contract" />
<com.getbase.floatingactionbutton.FloatingActionsMenu
android:id="#+id/menu_fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|bottom"
android:layout_margin="#dimen/fab_margin"
app:fab_labelStyle="#style/Etiquetas"
app:fab_addButtonColorNormal="?attr/colorPrimary"
app:fab_addButtonSize="normal"
app:fab_labelsPosition="left">
<com.getbase.floatingactionbutton.FloatingActionButton
android:id="#+id/accion_formulario"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:fab_colorNormal="?attr/colorAccent"
app:fab_icon="#drawable/ic_tablet"
app:fab_size="normal"
app:fab_title="Formulario" />
<com.getbase.floatingactionbutton.FloatingActionButton
android:id="#+id/accion_buscar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:fab_colorNormal="?attr/colorAccent"
app:fab_icon="#drawable/ic_search"
app:fab_size="normal"
app:fab_title="Nueva Búsqueda" />
</com.getbase.floatingactionbutton.FloatingActionsMenu>
</android.support.design.widget.CoordinatorLayout>
content_result_contract.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/reciclador"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="3dp"
android:layout_marginTop="20dp"
android:scrollbars="vertical" />
Dialog_contract.java
public class Dialog_contract extends DialogFragment implements DialogActions {
public static final String TAG = "fragment_dialog";
private TabLayout Tabs;
private Form_contract_detail fragment_detalles;
private Form_contract_observation fragment_obseration;
private Fragment fragment_observation;
View view_contract;
ViewPager pager;
PagerAdapter pagerAdapter;
Toolbar toolbar;
String title="Detalles ";
int cantidad;
public Dialog_contract(){
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void Dismiss()
{
getDialog().dismiss();
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
cantidad= Contract_list.getInstance().getList_contract().size();
view_contract=inflater.inflate(R.layout.dialog_contract, container, false);
pager=(ViewPager)view_contract.findViewById(R.id.pager);
pagerAdapter= new Dialog_contract_adapter(getActivity(), getChildFragmentManager(),Contract_list.getInstance().getList_contract().size());
toolbar = (Toolbar) view_contract.findViewById(R.id.toolbar);
((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
actionBar.setHomeAsUpIndicator(android.R.drawable.ic_menu_close_clear_cancel);
}
setHasOptionsMenu(true);
int position=getArguments().getInt("position", -1);
pager.setAdapter(pagerAdapter);
pager.setPageTransformer(true, new ZoomOutPageTransformer());
//pager.setPageTransformer(true,new DepthPageTransformer() );
pager.setCurrentItem(position);
pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener(){
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
updateTitle();
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
updateTitle();
return view_contract;
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog dialog = super.onCreateDialog(savedInstanceState);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
return dialog;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
getActivity().getMenuInflater().inflate(R.menu.dialog_contract_menu, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_next) {
pager.setCurrentItem(pager.getCurrentItem() + 1);
updateTitle();
return true;
} else if (id==R.id.action_previous)
{
pager.setCurrentItem(pager.getCurrentItem() - 1);
updateTitle();
return true;
}
else if (id == android.R.id.home) {
// handle close button click here
dismiss();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void updateTitle() {
toolbar.setTitle(title+String.valueOf(pager.getCurrentItem()+1)+"/"+cantidad);
}
}
dialog_contract.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
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:paddingTop="24dp"
android:fitsSystemWindows="true"
>
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay"
android:fitsSystemWindows="false"
>
<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:fitsSystemWindows="false"/>
</android.support.design.widget.AppBarLayout>
<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:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:orientation="vertical"
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">
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.view.PagerTabStrip
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"/>
</android.support.v4.view.ViewPager>
</LinearLayout>
First of all your dialog layout has top padding so that why it has no full height.
dialog_contract.xml
<android.support.design.widget.CoordinatorLayout
...
android:paddingTop="24dp"
>
Second of all try following java naming convention since your code is realy hard to read
Also when I click the close button of the Dialog it closes not only the dialog, but the activity as well, and goes to the previous activity.
My best guess is that you are not handling menu clicks correctly, try calling
setHasOptionsMenu(true);
from dialogFragmen onCreate

BottomNavigationView text overlaps on icon

I have used BottomNavigationView in my app, but the text of menu item overlaps on menu icon in small devices as shown in below screenshot.
Edit:
Here is the java code:
public class MainActivity extends AppCompatActivity {
private static final String SELECTED_ITEM = "arg_selected_item";
private BottomNavigationView mBottomNav;
private int mSelectedItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBottomNav = (BottomNavigationView) findViewById(R.id.navigation);
BottomNavigationViewHelper.disableShiftMode(mBottomNav);
mBottomNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
selectFragment(item);
return true;
}
});
MenuItem selectedItem;
if (savedInstanceState != null) {
mSelectedItem = savedInstanceState.getInt(SELECTED_ITEM, 0);
selectedItem = mBottomNav.getMenu().findItem(mSelectedItem);
} else {
selectedItem = mBottomNav.getMenu().getItem(0);
}
selectFragment(selectedItem);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putInt(SELECTED_ITEM, mSelectedItem);
super.onSaveInstanceState(outState);
}
#Override
public void onBackPressed() {
MenuItem homeItem = mBottomNav.getMenu().getItem(0);
if (mSelectedItem != homeItem.getItemId()) {
// select home item
selectFragment(homeItem);
} else {
super.onBackPressed();
}
}
private void selectFragment(MenuItem item) {
// init corresponding fragment
switch (item.getItemId()) {
case R.id.menu_explore:
pushFragment(new ExploreFragment());
break;
case R.id.menu_how_it_works:
pushFragment(new HowItWorksFragment());
break;
case R.id.menu_contact_us:
pushFragment(new ContactUsFragment());
break;
case R.id.menu_profile:
pushFragment(new MyProfileFragment());
break;
}
// update selected item
mSelectedItem = item.getItemId();
// uncheck the other items.
for (int i = 0; i < mBottomNav.getMenu().size(); i++) {
MenuItem menuItem = mBottomNav.getMenu().getItem(i);
menuItem.setChecked(menuItem.getItemId() == item.getItemId());
}
updateToolbarText(item.getTitle());
}
protected void pushFragment(Fragment fragment) {
if (fragment == null)
return;
FragmentManager fragmentManager = getFragmentManager();
if (fragmentManager != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
if (ft != null) {
ft.replace(R.id.container, fragment);
ft.commit();
}
}
}
private void updateToolbarText(CharSequence text) {
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setTitle(text);
}
}
}
Here is the xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:design="http://schemas.android.com/apk/res-auto"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<android.support.design.widget.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:background="#android:color/white"
design:menu="#menu/bottom_nav_items" />
</LinearLayout>
How to resolve this issue ?
Please Help!!
Do not use long texts on bottom bar. It's out of guideline. Bottom Bar is not developed to use like that.
Text labels provide short, meaningfully definitions to bottom
navigation icons. Avoid long text labels as these labels do not
truncate or wrap.
Read all documentation and usage descriptions at this Source.

Android "No view found for id for fragment"

Okay. I am stuck and having a headache... I am not sure how to access the other layout's view, since inflating does not work.
Here are my codes.
WriteRouteActivity.java
public class WriteRouteActivity extends AppCompatActivity {
private Toolbar tb;
private TextView txt_toolbar_title;
private Button btnSearchPlaces;
private LinearLayout parentLayout, placesCoverLayout;
private View popupView;
private ImageView imgShowPlaces;
private boolean isKeyBoardVisible;
private int keyboardHeight;
private EditText edtSearchPlaces;
private PopupWindow popupWindow;
//popupView
private TabLayout tabLayout;
private FrameLayout frameLayout;
//prework
private int minusVal;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_write_route);
initView();
}
private void initView() {
//for activity and native back button
tb = (Toolbar) findViewById(R.id.nav_toolbar);
setSupportActionBar(tb);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
txt_toolbar_title = (TextView) findViewById(R.id.txt_toolbar);
parentLayout = (LinearLayout) findViewById(R.id.layout_parent);
placesCoverLayout = (LinearLayout) findViewById(R.id.footer_for_places);
imgShowPlaces = (ImageView) findViewById(R.id.img_show_places);
edtSearchPlaces =(EditText) findViewById(R.id.edt_search_place);
btnSearchPlaces = (Button) findViewById(R.id.btn_search_place);
popupView = getLayoutInflater().inflate(R.layout.places_popup, null);
tabLayout = (TabLayout) popupView.findViewById(R.id.tab_layout);
frameLayout = (FrameLayout) popupView.findViewById(R.id.frame_layout);
doWorkForLayotus();
}
private void doWorkForLayotus(){
final float popUpheight = getResources().getDimension(R.dimen.keyboard_height);
changeKeyboardHeight((int) popUpheight);
enablePopUpView();
setTabLayout();
checkKeyboardHeight(parentLayout);
enableFooterView();
}
public void setCurrentTabFragment(int position) throws IllegalAccessException, InstantiationException {
String tag="";
Fragment fr = null;
Class frClass = null;
FragmentManager frManager = getSupportFragmentManager();
switch (position) {
case 0:
tag = "first";
//hide
if(frManager.findFragmentByTag("second")!=null){
frManager.beginTransaction().hide(frManager.findFragmentByTag("second")).commit();
}
if(frManager.findFragmentByTag("third")!=null){
frManager.beginTransaction().hide(frManager.findFragmentByTag("third")).commit();
}
if(frManager.findFragmentByTag("fourth")!=null){
frManager.beginTransaction().hide(frManager.findFragmentByTag("fourth")).commit();
}
//show
if(frManager.findFragmentByTag("first")!=null){
frManager.beginTransaction().show(frManager.findFragmentByTag("first")).commit();
}else{ //add
try {
frManager.beginTransaction().add(frameLayout.getId(), ((Fragment) Fragment_zasin.class.newInstance()), tag).commit();
}catch(Exception e){
Log.e("why", e.getMessage().toString());
}
}
break;
case 1:
tag = "second";
//hide
if(frManager.findFragmentByTag("first")!=null){
frManager.beginTransaction().hide(frManager.findFragmentByTag("first")).commit();
}
if(frManager.findFragmentByTag("third")!=null){
frManager.beginTransaction().hide(frManager.findFragmentByTag("third")).commit();
}
if(frManager.findFragmentByTag("fourth")!=null){
frManager.beginTransaction().hide(frManager.findFragmentByTag("fourth")).commit();
}
//show
if(frManager.findFragmentByTag("second")!=null){
frManager.beginTransaction().show(frManager.findFragmentByTag("second")).commit();
}else{ //add
frManager.beginTransaction().add(frameLayout.getId(), ((Fragment) Fragment_zasin.class.newInstance()), tag).commit();
}
break;
case 2:
tag = "third";
//hide
if(frManager.findFragmentByTag("first")!=null){
frManager.beginTransaction().hide(frManager.findFragmentByTag("first")).commit();
}
if(frManager.findFragmentByTag("second")!=null){
frManager.beginTransaction().hide(frManager.findFragmentByTag("second")).commit();
}
if(frManager.findFragmentByTag("fourth")!=null){
frManager.beginTransaction().hide(frManager.findFragmentByTag("fourth")).commit();
}
//show
if(frManager.findFragmentByTag("third")!=null){
frManager.beginTransaction().show(frManager.findFragmentByTag("third")).commit();
}else{ //add
frManager.beginTransaction().add(frameLayout.getId(), ((Fragment) Fragment_zasin.class.newInstance()), tag).commit();
}
break;
case 3:
tag = "fourth";
//hide
if(frManager.findFragmentByTag("first")!=null){
frManager.beginTransaction().hide(frManager.findFragmentByTag("first")).commit();
}
if(frManager.findFragmentByTag("second")!=null){
frManager.beginTransaction().hide(frManager.findFragmentByTag("second")).commit();
}
if(frManager.findFramentByTag("third")!=null){
frManager.beginTransaction().hide(frManager.findFragmentByTag("third")).commit();
}
//show
if(frManager.findFragmentByTag("fourth")!=null){
frManager.beginTransaction().show(frManager.findFragmentByTag("fourth")).commit();
}else{ //add
frManager.beginTransaction().add(R.id.frame_layout, ((Fragment) Fragment_zasin.class.newInstance()), tag).commit();
}
break;
}
//frManager.beginTransaction().replace(R.id.frame_container, fr, tag).setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).commit();
}
private void setTabLayout(){
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
try {
setCurrentTabFragment(tab.getPosition());
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
private void enablePopUpView() {
// Creating a pop window for emoticons keyboard
popupWindow = new PopupWindow(popupView, ViewGroup.LayoutParams.MATCH_PARENT,
(int) keyboardHeight, false);
popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
#Override
public void onDismiss() {
placesCoverLayout.setVisibility(LinearLayout.GONE);
}
});
}
int previousHeightDiffrence = 0;
private void checkKeyboardHeight(final View parentLayout) {
parentLayout.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
Rect r = new Rect();
parentLayout.getWindowVisibleDisplayFrame(r);
int screenHeight = parentLayout.getRootView()
.getHeight();
minusVal=screenHeight-r.bottom;
int heightDifference = screenHeight - (r.bottom+(minusVal));
if (previousHeightDiffrence - heightDifference > 50) {
popupWindow.dismiss();
}
previousHeightDiffrence = heightDifference;
if (heightDifference > 100) {
isKeyBoardVisible = true;
changeKeyboardHeight(heightDifference);
} else {
isKeyBoardVisible = false;
}
}
});
}
private void changeKeyboardHeight(int height) {
if (height > 100) {
keyboardHeight = height;
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, keyboardHeight);
placesCoverLayout.setLayoutParams(params);
}
}
private void enableFooterView() {
edtSearchPlaces.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (popupWindow.isShowing()) {
popupWindow.dismiss();
}
}
});
btnSearchPlaces.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
hideSoftKeyboard(WriteRouteActivity.this);
if(!popupWindow.isShowing()){
popupWindow.setHeight((int) (keyboardHeight));
if (isKeyBoardVisible) {
placesCoverLayout.setVisibility(LinearLayout.GONE);
} else {
placesCoverLayout.setVisibility(LinearLayout.VISIBLE);
}
popupWindow.setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED);
popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
popupWindow.showAtLocation(parentLayout, Gravity.BOTTOM, 0, 0);
try {
setCurrentTabFragment(0);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
} else {
//popupWindow.dismiss();
}
}
});
}
#Override
protected void onDestroy() {
popupWindow.dismiss();
super.onDestroy();
}
public static void hideSoftKeyboard(Activity activity) {
InputMethodManager inputMethodManager =
(InputMethodManager) activity.getSystemService(
Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(
activity.getCurrentFocus().getWindowToken(), 0);
}
#Override
public void onBackPressed() {
if(popupWindow.isShowing()){
popupWindow.dismiss();
}else {
super.onBackPressed();
}
}
}
activity_write_wroute.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout_parent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout="#layout/nav_toolbar" />
<fragment
android:id="#+id/google_map"
class="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<include
android:id="#+id/footer_layout"
layout="#layout/footer_edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:id="#+id/footer_for_places"
android:layout_width="match_parent"
android:layout_height="#dimen/keyboard_height"
android:background="#android:color/transparent"
android:orientation="vertical"
android:visibility="gone" />
</LinearLayout>
Fragment_Zasin
public class Fragment_zasin extends Fragment {
public Fragment_zasin newInstance() {
Fragment_zasin fr = new Fragment_zasin();
return fr;
}
public Fragment_zasin() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_zasin, container, false);
return rootView;
}
}
places_popup.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/linear_layout_top"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#fff"
android:orientation="vertical">
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
android:layout_width="fill_parent"
android:layout_height="?attr/actionBarSize"
android:background="#ffffff"
app:tabGravity="fill"
app:tabIndicatorColor="#color/colorPrimary"
app:tabIndicatorHeight="4dp"
app:tabMode="fixed"
app:tabSelectedTextColor="#color/colorPrimary">
<android.support.design.widget.TabItem
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:icon="#drawable/tab_pin_selector"
android:text="11">
</android.support.design.widget.TabItem>
<android.support.design.widget.TabItem
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:icon="#drawable/tab_mainroute_selector"
android:text="22" />
<android.support.design.widget.TabItem
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:icon="#drawable/tab_talk_selector"
android:text="33" />
<android.support.design.widget.TabItem
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:icon="#drawable/tab_my_selector"
android:text="44" />
</android.support.design.widget.TabLayout>
<FrameLayout
android:id="#+id/frame_layout"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1" />
</LinearLayout>
LOGCAT Message
FATAL EXCEPTION: main Process: suacuration.itgotravel, PID: 20131
java.lang.IllegalArgumentException: No view found for id 0x7f100173 for fragment Fragment_zasin{d4ac39c #0 id=0x7f100173 first}
Can somebody help this?
This error occurs because the fragment manager could not find the view on which it has to inflate the fragment.
The fragment transaction is linked to the activity so this error occurs as the frame layout is not a part of that main activity's xml.so it cant find where to add the fragment.fragment has to be added inside the activity.
what you have to do is provide the id of a view in your main activity.
for e.g your main view
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout_parent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/mainView"//like this
android:orientation="vertical">
<include layout="#layout/nav_toolbar" />
<fragment
android:id="#+id/google_map"
class="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<include
android:id="#+id/footer_layout"
layout="#layout/footer_edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:id="#+id/footer_for_places"
android:layout_width="match_parent"
android:layout_height="#dimen/keyboard_height"
android:background="#android:color/transparent"
android:orientation="vertical"
android:visibility="gone" />
</LinearLayout>
The view where you are trying to inflate the fragemnt must be inside activity.
Now when you try
frManager.beginTransaction().add(R.id.mainView, ((Fragment) Fragment_zasin.class.newInstance()), tag).commit();
the fragment will be loaded on this view of your activity.
Problem is you are trying to show a Fragment on a View which is not defined in your layout which you have defined in your onCreate() while setContentView(layoutId)
In your case you are inflating fragments in WriteRouteActivity where layout defined is activity_write_route and fragments are added on FrameLayout which is defined in places_popup.xml so define your framelayout in a view layout of Activity.
Small Description :
--------code------
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
-------layout define for activity-------
setContentView(R.layout.activity_write_route);
}
now where you are adding fragment on a FrameLayout(view)
frManager.beginTransaction().add(R.id.frame_layout, ((Fragment) Fragment_zasin.class.newInstance()), tag).commit();
here R.id.frame_layout should be define in your layout activity_write_route.
Okay i found an answer.
The problem was that fragment cannot be a child of a 'Dialog'.
Since i used popup dialog, it was unable to put fragments inside the dialog.
i solved by inflating views rather than using fragments in tablayout.
There could be other errors but what is this?
tb = (Toolbar) findViewById(R.id.nav_toolbar);
This is not a toolbar:
<include layout="#layout/nav_toolbar" />
Can we see inside this nav_toolbar layout?
Also, where is this: "R.layout.fragment_zasin". It's complaining about a Fragment so it would be worthwhile seeing if this is ok.
Anyway, as a general troubleshooting strategy, try commenting out all those lines in the initView() method and just add them in one at a time until it fails. Or maybe if you scroll down in the error logs further it will give you a hyperlink to the line that's causing it to fail.
Why do you have "frameLayout.getId()" on one line but "R.id.frame_layout" on another? Try to use the latter for all of the lines and see if that's it.
I was extending the wrong type of activity, extended AppCompact solved issue.
Got this error when starting new fragment from fragment, using ChildFragmentManager, and giving id of container from activity, in transaction replace method.
It happens that FragmentManager has access to activity containers, but ChildFragmentManager has access to fragment containers.
The solution was to use FragmentManager class instead of ChildFragmentManager.
You got this error because your view found for id 0x7f100173 into fragment Fragment_zasin so only solution is that:
1) check all id present to that particular layout.
2) if all id is present to that particular layout and still you facing same issue do one thing change name of id don't refactor change name and access this changed id name in your fragment or activity.

Up Navigation (Action Bar's back arrow) is not working for fragments

I've drawer-layout as a base layout of my activity and I'm replacing two fragments on a frame present inside this drawer-layout. The first fragment is not added in fragment's back stack. I'm displaying hamburger icon in my activity (I also want the drawer menu in my first fragment). In second fragment I disabled the hamburger icon by mActionBarDrawerToggle.setDrawerIndicatorEnabled(false) and enabled back button using actionBar.setDisplayHomeAsUpEnabled(true).
In first fragments onResume I enabled hamburger icon by mActionBarDrawerToggle.setDrawerIndicatorEnabled(true)` so that when user presses back button (both hardware and action-bar's up button) from second fragment,user will come back to first fragment and hamburger icon will be enabled. Everything is working fine only I'm not able to go back from second fragments action bar back button. I'm not able to click it.
Below is my code :-
Activity code
if (Utility.isLargeScreen(this))
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
else
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
mHiddenGemsApplication = (HiddenGemsApplication) getApplication();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
initViews();
setSupportActionBar(mToolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayHomeAsUpEnabled(true);
}
mTextViewActionBarTitle.setText(getString(R.string.app_name));
mActionBarDrawerToggle = new ActionBarDrawerToggle(HomeActivity.this, mDrawerLayout, mToolbar, R.string.open_drawer, R.string.close_drawer) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
mDrawerLayout.setDrawerListener(mActionBarDrawerToggle);
mActionBarDrawerToggle.syncState();
mFragmentManager = getSupportFragmentManager();
replaceFragment(new CategoryFragment(), getString(R.string.app_name), CategoryFragment.TAG);
#Override
public void onBackPressed() {
if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
mDrawerLayout.closeDrawers();
return;
}
super.onBackPressed();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
if (mFragmentManager.getBackStackEntryCount() > 0) {
mFragmentManager.popBackStack();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void replaceFragment(Fragment fragment, String actionBarTitle, String tag) {
if (mFragmentManager == null)
return;
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.content_frame, fragment, tag);
if (!tag.equals(CategoryFragment.TAG))
fragmentTransaction.addToBackStack(tag);
fragmentTransaction.commit();
setActionBarTitle(actionBarTitle);
}
public void setActionBarTitle(String actionBarTitle) {
if (!TextUtils.isEmpty(actionBarTitle))
mTextViewActionBarTitle.setText(actionBarTitle);
}
public void setDrawerIndicatorEnabled(boolean value) {
if (mActionBarDrawerToggle != null) {
mActionBarDrawerToggle.setDrawerIndicatorEnabled(value);
}
}
Activity 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/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="nirvaniclabs.com.hiddengems.activities.HomeActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<include
android:id="#+id/toolbarlayout"
layout="#layout/toolbar_layout" />
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/toolbarlayout" />
</RelativeLayout>
<android.support.design.widget.NavigationView
android:id="#+id/navigation"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:menu="#menu/navigation_items" />
</android.support.v4.widget.DrawerLayout>
First Fragment : -
private Button mButtonTemp;
private AppCompatActivity mActivity;
public static String TAG = "CategoryFragment";
public CategoryFragment() {
// Required empty public constructor
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof Activity)
mActivity = (AppCompatActivity) context;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View viewGroup = inflater.inflate(R.layout.fragment_category, container, false);
initViews(viewGroup);
mButtonTemp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((HomeActivity) mActivity).replaceFragment(new TripListFragment(), "Trip Fragment", TripListFragment.TAG);
}
});
return viewGroup;
}
private void initViews(View viewGroup) {
mButtonTemp = (Button) viewGroup.findViewById(R.id.btn_temp);
}
#Override
public void onResume() {
super.onResume();
((HomeActivity) mActivity).setDrawerIndicatorEnabled(true);
((HomeActivity) mActivity).setActionBarTitle(getString(R.string.app_name));
}
Second Fragment
private AppCompatActivity mActivity;
public static String TAG = "TripListFragment";
public TripListFragment() {
// Required empty public constructor
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof Activity)
mActivity = (AppCompatActivity) context;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
ActionBar actionBar = mActivity.getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_trip_list, container, false);
}
#Override
public void onResume() {
super.onResume();
((HomeActivity) mActivity).setDrawerIndicatorEnabled(false);
}
Also, when I'm in second fragment I'm able to swipe and see the drawer menu. I don't want this behaviour, drawer menu should only open in fragment 1.
If any thing is wrong in my code please let me know.
Finally got the answer. In my scenario I'm disabling the drawer indicator by mActionBarDrawerToggle.setDrawerIndicatorEnabled(false); and due to this Navigation icon clicks got disabled. To enable this I've to add ToolbarNavigationClickListener to ActionBarDrawerToggle which will enable navigation icon clicks.
Below is the my working code :-
mActionBarDrawerToggle.setToolbarNavigationClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
Refer this link for more clarification
After struggling with the same problem for ages, I eventually managed to get the Up button to work in fragments with this code.
You must have setHasOptionsMenu set up in onCreate() or onCreateView()
setHasOptionsMenu(true);
Then, in onOptionsItemSelected() add this check for the up / home button being pressed to your switch() [or if...] statement:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
x.L();
switch (item.getItemId()) {
case android.R.id.home :
getActivity().onBackPressed();
break;
case R.id.mn_exit :
exitFragment();
break;
default :
break;
}
return super.onOptionsItemSelected(item);
}

Categories

Resources