Raj Patel Raj Patel - 6 months ago 70
Android Question

How to up navigate from fragment activity?

Hi I am having trouble while going back to parent activity from fragment activity. I want back arrow at top left corner inside the action bar.

I am able to show it in action bar activity using this code

getSupportActionBar().setDisplayShowHomeEnabled(true);


But I am not able to do it in tabbed activity's fragment.

((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayShowHomeEnabled(true);


Please Help me!!

Update
It worked before as suggested by vrund but now again it stopped working. It shows the back arrow on top left corner but when I click on it, it does nothing my code is as follow.

AlgorithmActivity.java

package com.suvariyaraj.algorithms;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Intent;
import android.support.design.widget.TabLayout;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.getbase.floatingactionbutton.FloatingActionButton;
import com.getbase.floatingactionbutton.FloatingActionsMenu;

import org.w3c.dom.Text;

public class AlgorithmActivity extends AppCompatActivity {

/**
* The {@link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {@link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {@link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;

/**
* The {@link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
String title;

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


Intent i = getIntent();
title = i.getStringExtra("Subsection");
//Toast.makeText(getApplicationContext(), title, Toast.LENGTH_SHORT).show();

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);**
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);

TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);

FloatingActionButton fab_copy = (FloatingActionButton) findViewById (R.id.fab_copy);
FloatingActionButton fab_share = (FloatingActionButton) findViewById (R.id.fab_share);
FloatingActionButton fab_doubt = (FloatingActionButton) findViewById (R.id.fab_doubt);
final FloatingActionsMenu fab_menu = (FloatingActionsMenu) findViewById (R.id.fab_menu);

if (fab_copy != null) {
fab_copy.setOnClickListener (new View.OnClickListener () {
@Override
public void onClick(View v) {
String s= "";
for(int i=1;;i++){
View tempv = findViewById (i);
if(tempv==null){
break;
}
else{
if (tempv instanceof ImageView) {
ImageView imageView = (ImageView) tempv;
// do what you want with imageView
s+="\n<<Download the app to view the Image>>\n";
}
else if (tempv instanceof TextView) {
TextView textView = (TextView) tempv;
// do what you want with textView
s+=textView.getText ();
}
}
}
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("abc", s);
clipboard.setPrimaryClip(clip);
Toast.makeText (getApplicationContext (),"Content Copied",Toast.LENGTH_SHORT).show ();
fab_menu.collapse ();
}
});
}

if (fab_share != null) {
fab_share.setOnClickListener (new View.OnClickListener () {
@Override
public void onClick(View v) {
String s= "This message is generated using Algorithms app by Raj, Tejasv and Karan \n\n";
for(int i=1;;i++){
View tempv = findViewById (i);
if(tempv==null){
break;
}
else{
if (tempv instanceof ImageView) {
ImageView imageView = (ImageView) tempv;
// do what you want with imageView
s+="\n<<Download the app to view the Image>>\n";
}
else if (tempv instanceof TextView) {
TextView textView = (TextView) tempv;
// do what you want with textView
s+=textView.getText ();
}
}
}
fab_menu.collapse ();
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, s);
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, "Share using..."));
}
});
}

if (fab_doubt != null) {
fab_doubt.setOnClickListener (new View.OnClickListener () {
@Override
public void onClick(View v) {
Intent i = new Intent (getApplicationContext (), DoubtActivity.class);
i.putExtra ("Title", title);
fab_menu.collapse ();
startActivity (i);
}
});
}
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_algorithm, menu);
return false;
}

@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;
}
if (item.getItemId() == android.R.id.home) {
onBackPressed();
}

return super.onOptionsItemSelected(item);
}

/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";

public PlaceholderFragment() {
}

/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// ((AlgorithmActivity)getActivity()).getSupportActionBar().setDisplayShowHomeEnabled(true);

View rootView = inflater.inflate(R.layout.fragment_algorithm, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
String[] array = {"Hi from description", "Hi from C", "Hi from JAVA"};
array[0] = "Hi! this is the first program of asdk your carrier into computer coding. This code shows you how to print Hello World on the console of the computer!\n\nHere is the Image \n\nThis image shows you how this program works! Wohoo you learnt the first ``Image:star`` algo of your life. sdiaj isja dias dsa djsa djas sadksf dsfsdmf sdf ldsf ldsfsdl fsdkf s fsd lksd flsdkl flkds lsdkflklsdk flksdlfklsdl fklsdkl flsdkf klkd b jj bbb jhbhb hjbhj bjh bhjbhjbhjb jbhjb hjbhbhbhjbhbhbhhjb hbhjbh b hjb hj bhjbhj hb hjb ``Image:youtube`` jh bhjbhjbhjhbh bbhskflkldsl jghu vugyuh uuuububu";

NestedScrollView scrollView = (NestedScrollView) rootView.findViewById(R.id.abcscrollView);
LinearLayout linearLayout = new LinearLayout (rootView.getContext ());
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
linearLayout.setLayoutParams (params);
linearLayout.setOrientation (LinearLayout.VERTICAL);

if(getArguments().getInt(ARG_SECTION_NUMBER)-1==0) {
String temparray[] = array[0].split("``");
array[0] = "";
for (int i = 0; i < temparray.length; i++) {
if (temparray[i].startsWith("Image:")) {
ImageView iv = new ImageView(rootView.getContext());
iv.setId(i+1);
int itd = this.getResources().getIdentifier(temparray[i].substring(6), "drawable", getActivity().getPackageName());
iv.setImageResource(itd);
linearLayout.addView (iv);

} else {
TextView tv = new TextView(rootView.getContext());
tv.setText(temparray[i]);
tv.setTextSize (24);
tv.setId(i+1);
linearLayout.addView (tv);
}
}
}
NestedScrollView.LayoutParams params2 = new NestedScrollView.LayoutParams (NestedScrollView.LayoutParams.MATCH_PARENT, NestedScrollView.LayoutParams.MATCH_PARENT);
scrollView.addView (linearLayout,params2);

textView.setText (array[getArguments ().getInt (ARG_SECTION_NUMBER) - 1]);
return rootView;
}
}

/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {

public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}

@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}

@Override
public int getCount() {
// Show 3 total pages.
return 3;
}

@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Description";
case 1:
return "C";
case 2:
return "Java";
}
return null;
}
}
}


xml code

<?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"
xmlns:fab="http://schemas.android.com/apk/res-auto"
android:id="@+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.suvariyaraj.algorithms.AlgorithmActivity">

<android.support.design.widget.AppBarLayout
android:id="@+id/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"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="@style/AppTheme.PopupOverlay">

</android.support.v7.widget.Toolbar>

<android.support.design.widget.TabLayout
android:id="@+id/tabs"
app:tabTextColor="@color/tabbackground"
app:tabTextAppearance="@style/tabTextStyle"
app:tabIndicatorColor="@color/tabbackground"
app:tabIndicatorHeight="4dp"
app:tabBackground="@color/colorPrimary"

android:layout_width="match_parent"
android:layout_height="wrap_content" />

</android.support.design.widget.AppBarLayout>

<android.support.v4.view.ViewPager
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
>
</android.support.v4.view.ViewPager>

<!--<android.support.design.widget.FloatingActionButton-->
<!--android:id="@+id/fab"-->
<!--android:layout_width="wrap_content"-->
<!--android:layout_height="wrap_content"-->
<!--android:layout_gravity="end|bottom"-->
<!--android:layout_margin="@dimen/fab_margin"-->
<!--android:src="@android:drawable/ic_dialog_email" />-->



<com.getbase.floatingactionbutton.FloatingActionsMenu
android:id="@+id/fab_menu"
android:layout_gravity="end|bottom"
android:layout_marginRight="10sp"
android:layout_marginBottom="10sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
fab:fab_addButtonColorNormal="@color/colorAccent"
fab:fab_addButtonColorPressed="@color/colorAccent"
fab:fab_addButtonPlusIconColor="@android:color/white"
fab:fab_addButtonSize="normal"
fab:fab_addButtonStrokeVisible="false"
fab:fab_labelStyle="@style/menu_labels_style"
fab:fab_expandDirection="up"
>

<com.getbase.floatingactionbutton.FloatingActionButton
android:id="@+id/fab_doubt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
fab:fab_colorNormal="@color/colorPrimary"
fab:fab_colorPressed="@color/colorPrimaryDark"
fab:fab_icon="@drawable/doubt_icon"
fab:fab_title="Ask a doubt"/>

<com.getbase.floatingactionbutton.FloatingActionButton
android:id="@+id/fab_share"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
fab:fab_colorNormal="@color/colorPrimary"
fab:fab_colorPressed="@color/colorPrimaryDark"
fab:fab_icon="@drawable/share_icon"
fab:fab_title="Share"/>

<com.getbase.floatingactionbutton.FloatingActionButton
android:id="@+id/fab_copy"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
fab:fab_colorNormal="@color/colorPrimary"
fab:fab_colorPressed="@color/colorPrimaryDark"
fab:fab_icon="@drawable/copy_icon"
fab:fab_title="Copy Content"/>

</com.getbase.floatingactionbutton.FloatingActionsMenu>




Manifest Code :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.suvariyaraj.algorithms">

<application
android:allowBackup="true"
android:icon="@mipmap/app_icon3"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>

<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity
android:name=".SubSectionActivity"
android:parentActivityName=".MainActivity"/>
<activity
android:name=".AlgorithmActivity"
android:label="@string/title_activity_algorithm"
android:theme="@style/AppTheme.NoActionBar"
android:parentActivityName=".SubSectionActivity"/>
<activity
android:theme="@android:style/Theme.Dialog"
android:name=".DoubtActivity"
android:parentActivityName=".AlgorithmActivity">
</activity>
</application>

</manifest>


But this code shows me that mSectionsPagerAdapter, mViewPager, and getSupportActionBar().setDisplayHomeAsUpEnabled(true); can return nullPointer and the up nevigation is not working.

Answer

Add this inside onCreate() of your tabbed activity,

toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);

And for navigating back, you need to override following method in your tabbed activity.

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            onBackPressed();
        }
        return super.onOptionsItemSelected(item);
    }

Happy coding.

Comments