I'm new to the android. I've an activity with 5 fragments and I've used addTobackStack so that I can move to the previous fragments when back button is clicked. It does the work but I want to call the functions in which I've been replacing the fragments when back button is pressed.
Any help?
Here is the code.
Dashboard.java
package com.example.sheikhspc.design;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.Fragment;
import android.content.Intent;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class dashboard extends AppCompatActivity {
ImageView home1, subs1, noti1,settings1,date1;
Fragment frag = null;
TextView home, subs,noti,set,date;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
home1 = (ImageView) findViewById(R.id.home1);
subs1 = (ImageView) findViewById(R.id.subs1);
noti1 = (ImageView) findViewById(R.id.noti1);
settings1 = (ImageView) findViewById(R.id.settings1);
date1 = (ImageView) findViewById(R.id.date1);
frag = new dashboard1();
home = (TextView)findViewById(R.id.hometv);
subs = (TextView)findViewById(R.id.substv);
noti = (TextView)findViewById(R.id.notitv);
set = (TextView)findViewById(R.id.settingstv);
date = (TextView)findViewById(R.id.datestv);
FragmentManager fm = getFragmentManager();
fm.beginTransaction().add(R.id.container1,frag).commit();
Toolbar mytoolbar = (Toolbar)findViewById(R.id.mytoolbar);
setSupportActionBar(mytoolbar);
getSupportActionBar().setTitle("Home");
home.setTextColor(0xFF000000);
}
public void dbfragment(View view)
{
if(frag != null)
{
home1.setBackgroundDrawable(getResources().getDrawable(R.drawable.home_icon_black) ome1.setBackgroundDrawable(getResources().getDrawable(R.drawable.home_icon_black) );
home.setTextColor(0xFF000000);
subs1.setBackgroundDrawable(getResources().getDrawable(R.drawable.subscription_ic on));
noti1.setBackgroundDrawable(getResources().getDrawable(R.drawable.noti_icon));
settings1.setBackgroundDrawable(getResources().getDrawable(R.drawable.setting_icon));
date1.setBackgroundDrawable(getResources().getDrawable(R.drawable.date_icon));
date1.setBackgroundDrawable(getResources().getDrawable(R.drawable.d))
frag = new dashboard1();
getSupportActionBar().setTitle("Home");
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.container1,frag);
fragmentTransaction.commit();
}
}
public void dates(View view)
{
if(frag != null)
{
home1.setBackgroundDrawable(getResources().getDrawable(R.drawable.home_icon));
subs1.setBackgroundDrawable(getResources().getDrawable(R.drawable.subscription_icon));
noti1.setBackgroundDrawable(getResources().getDrawable(R.drawable.noti_icon));
settings1.setBackgroundDrawable(getResources().getDrawable(R.drawable.setting_icon));
date1.setBackgroundDrawable(getResources().getDrawable(R.drawable.date_icon_black));
date.setTextColor(0xFF000000);
getSupportActionBar().setTitle("Available Dates");
frag = new AvailableDates();
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.container1,frag);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}
public void subscription(View view)
{
if (frag != null)
{
home1.setBackgroundDrawable(getResources().getDrawable(R.drawable.home_icon));
subs1.setBackgroundDrawable(getResources().getDrawable(R.drawable.subscription_icon_black));
noti1.setBackgroundDrawable(getResources().getDrawable(R.drawable.noti_icon));
settings1.setBackgroundDrawable(getResources().getDrawable(R.drawable.setting_icon));
date1.setBackgroundDrawable(getResources().getDrawable(R.drawable.date_icon));
subs.setTextColor(0xFF000000);
getSupportActionBar().setTitle("Subscriptions");
frag = new Subscription();
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.container1,frag);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}
public void noti(View view)
{
getSupportActionBar().setTitle("Notifications");
if (frag != null)
{
home1.setBackgroundDrawable(getResources().getDrawable(R.drawable.home_icon));
subs1.setBackgroundDrawable(getResources().getDrawable(R.drawable.subscription_icon));
noti1.setBackgroundDrawable(getResources().getDrawable(R.drawable.noti_icon_black));
settings1.setBackgroundDrawable(getResources().getDrawable(R.drawable.setting_icon));
noti.setTextColor(0xFF000000);
date1.setBackgroundDrawable(getResources().getDrawable(R.drawable.date_icon));
frag = new Notification();
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.container1,frag);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}
public void settings(View view)
{
getSupportActionBar().setTitle("Settings");
if (frag != null)
{
set.setTextColor(0xFF000000);
home1.setBackgroundDrawable(getResources().getDrawable(R.drawable.home_icon));
subs1.setBackgroundDrawable(getResources().getDrawable(R.drawable.subscription_icon));
noti1.setBackgroundDrawable(getResources().getDrawable(R.drawable.noti_icon));
settings1.setBackgroundDrawable(getResources().getDrawable(R.drawable.setting_ion_black));
date1.setBackgroundDrawable(getResources().getDrawable(R.drawable.date_icon));
frag = new Settings();
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.container1,frag);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}
public void signout(View view)
{
Intent intent = new Intent(this, Login.class);
startActivity(intent);
}
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() > 0 ){
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
}
Activity_dashboard.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_dashboard"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white"
tools:context="com.example.sheikhspc.design.dashboard">
<include layout="#layout/toolbar"
android:id="#+id/mytoolbar"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/background"
android:layout_below="#id/mytoolbar">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/headrl"
android:paddingTop="5dp"
android:paddingRight="20dp"
android:paddingLeft="20dp"
android:paddingBottom="5dp"
android:background="#color/white"
tools:ignore="NotSibling">
<!-- <Button
android:text=""
android:background="#drawable/subscription_icon_black"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/notificationbtn"
android:onClick="subscription"
android:layout_marginLeft="10dp"
android:layout_marginStart="10dp"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/adbtn"
android:layout_toEndOf="#+id/adbtn"
android:layout_marginTop="7dp" />-->
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/home_icon_black"
android:onClick="dbfragment"
android:id="#+id/home1"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Home"
android:layout_below="#+id/home1"
android:id="#+id/hometv"
android:textSize="10dp"
android:layout_marginTop="2dp"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/date_icon"
android:onClick="dates"
android:id="#+id/date1"
android:layout_marginLeft="30dp"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/home1"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Dates"
android:layout_below="#+id/date1"
android:textSize="10dp"
android:id="#+id/datestv"
android:layout_marginLeft="30dp"
android:layout_toRightOf="#+id/home1"
android:layout_marginTop="0dp"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/noti_icon"
android:onClick="noti"
android:id="#+id/noti1"
android:layout_marginLeft="35dp"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/date1"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Notifications"
android:layout_below="#+id/noti1"
android:textSize="10dp"
android:id="#+id/notitv"
android:layout_marginLeft="15dp"
android:layout_toRightOf="#+id/date1"
android:layout_marginTop="0dp"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/subscription_icon"
android:onClick="subscription"
android:id="#+id/subs1"
android:layout_marginLeft="35dp"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/noti1"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Subscription"
android:layout_below="#+id/noti1"
android:textSize="10dp"
android:layout_marginLeft="25dp"
android:id="#+id/substv"
android:layout_toRightOf="#+id/noti1"
android:layout_marginTop="0dp"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/setting_icon"
android:onClick="settings"
android:id="#+id/settings1"
android:layout_marginLeft="35dp"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/subs1"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Settings"
android:layout_below="#+id/noti1"
android:textSize="10dp"
android:id="#+id/settingstv"
android:layout_marginLeft="30dp"
android:layout_toRightOf="#+id/subs1"
android:layout_marginTop="0dp"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/logout_icon"
android:onClick="signout"
android:id="#+id/signout1"
android:layout_marginLeft="35dp"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/settings1"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Logout"
android:layout_below="#+id/noti1"
android:textSize="10dp"
android:layout_marginLeft="30dp"
android:layout_toRightOf="#+id/settings1"
android:layout_marginTop="0dp"/>
<!--<Button
android:text=""
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/adbtn"
android:onClick="dates"
android:layout_marginTop="7dp"
android:layout_marginLeft="10dp"
android:background="#drawable/date_icon_black"
android:layout_toRightOf="#+id/dbbtn" />
<Button
android:text=""
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/dbbtn"
android:layout_marginTop="7dp"
android:background="#drawable/home_icon_black"
android:onClick="dbfragment"
android:layout_marginLeft="10dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />-->
</RelativeLayout>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/headrl"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/Black"
android:id="#+id/container1">
</RelativeLayout>
</ScrollView>
</RelativeLayout>
You can implement the FragmentManager.OnBackStackChangedListener and call your methods there depending upon which fragment is currently in the back stack. As I understand, currently the methods are called via touch interactions like button clicks. You wouldn't be able to do this on backstack change and need to figure out an alternate way.
You need to implement OnBackStackChangedListener in the activity. Better do the following in onCreate in your dashboard.java:
fragmentManager = getFragmentManager();
fragmentManager.addOnBackStackChangedListener(this);
Then override onBackStackChanged in your dashboard.java like this:
#Override
public void onBackStackChanged() {
//get the current fragment being displayed
Fragment fragment = fragmentManager.findFragmentById(R.id.container1);
if (fragment instanceof AvailableDates) {
//do your stuff
} else if (fragment instanceof Subscription) {
//do other stuff
} //and so on for each fragment
}
You can make different implementations for your onClick methods like thus:
public void dates(View view)
{
if(frag != null)
{
openAvailableDates();
}
}
and then implement openAvailableDates thus:
void openAvailableDates() {
home1.setBackgroundDrawable(getResources().getDrawable(R.drawable.home_icon));
subs1.setBackgroundDrawable(getResources().getDrawable(R.drawable.subscription_icon));
noti1.setBackgroundDrawable(getResources().getDrawable(R.drawable.noti_icon));
settings1.setBackgroundDrawable(getResources().getDrawable(R.drawable.setting_icon));
date1.setBackgroundDrawable(getResources().getDrawable(R.drawable.date_icon_black));
date.setTextColor(0xFF000000);
getSupportActionBar().setTitle("Available Dates");
frag = new AvailableDates();
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.container1,frag);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
and so on for your other methods and then call these new methods from onBackStackChanged.
One more tip. It's not good practice to name your classes starting with a lowercase letter. It's best to refactor dashboard.java to Dashboard.java.
Let me know if you need more help.
Related
if i have three fragments and i need to replace specific one by another how can i do this ? and how does replace method work in fragment transaction ? i find it replace one fragment by another if i have one fragment visible but if i have two fragments visible it replace a random one and if i have 4 fragments it replace two fragments by one!
in this program below i tried to add 4 fragments by using (add A) and (add B) Buttons but the problem exists when i try to use (replace A with B) or (replace B with A) buttons this will replace random fragment by fragment A or B.
Main Activity
package com.example.muhammad_adel.transaction;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
FragmentManager manager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
manager = getFragmentManager();
}
public void addA(View view) {
FragmentTransaction transaction = manager.beginTransaction();
FragmentA fragmentA = new FragmentA();
transaction.add(R.id.linearLayout, fragmentA, "addA");
transaction.commit();
}
public void removeA(View view) {
FragmentA fragmentA = (FragmentA) manager.findFragmentByTag("addA");
if (fragmentA != null && fragmentA.isVisible()) {
FragmentTransaction transaction = manager.beginTransaction();
transaction.remove(fragmentA);
transaction.commit();
}
}
public void replaceAwithB(View view) {
FragmentB fragmentB = new FragmentB();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.linearLayout, fragmentB, "addB");
transaction.commit();
}
public void addB(View view) {
FragmentB fragmentB = new FragmentB();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.linearLayout, fragmentB, "addB");
transaction.commit();
}
public void removeB(View view) {
FragmentB fragmentB = (FragmentB) manager.findFragmentByTag("addB");
if (fragmentB != null && fragmentB.isVisible()) {
FragmentTransaction transaction = manager.beginTransaction();
transaction.remove(fragmentB);
transaction.commit();
}
}
public void replaceBwithA(View view) {
FragmentA fragmentA = new FragmentA();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.linearLayout, fragmentA, "addA");
transaction.commit();
}
public void attachA(View view) {
FragmentA fragmentA = (FragmentA) manager.findFragmentByTag("addA");
if (fragmentA != null && !fragmentA.isVisible()) {
FragmentTransaction transaction = manager.beginTransaction();
transaction.attach(fragmentA);
transaction.commit();
}
}
public void attachB(View view) {
FragmentB fragmentB = (FragmentB) manager.findFragmentByTag("addB");
if (fragmentB != null && !fragmentB.isVisible()) {
FragmentTransaction transaction = manager.beginTransaction();
transaction.attach(fragmentB);
transaction.commit();
}
}
public void DetachedA(View view) {
FragmentA fragmentA = (FragmentA) manager.findFragmentByTag("addA");
if (fragmentA != null && fragmentA.isVisible()) {
FragmentTransaction transaction = manager.beginTransaction();
transaction.detach(fragmentA);
transaction.commit();
}
}
public void DetachedB(View view) {
FragmentB fragmentB = (FragmentB) manager.findFragmentByTag("addB");
if (fragmentB != null && fragmentB.isVisible()) {
FragmentTransaction transaction = manager.beginTransaction();
transaction.detach(fragmentB);
transaction.commit();
}
}}
public void replaceAOnlyWithB(View view) {
}
FragmentA
package com.example.muhammad_adel.transaction;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentA extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_a, container, false);
}
}
FragmentB
package com.example.muhammad_adel.transaction;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentB extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_b, container, false);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.muhammad_adel.transaction.MainActivity"
android:orientation="vertical">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add A"
android:id="#+id/button"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textAllCaps="false"
android:onClick="addA"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Remove A"
android:id="#+id/button2"
android:layout_alignBottom="#+id/button"
android:layout_toRightOf="#+id/button"
android:layout_toEndOf="#+id/button"
android:textAllCaps="false"
android:onClick="removeA"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Replace A with B"
android:id="#+id/button3"
android:layout_alignBottom="#+id/button2"
android:layout_toRightOf="#+id/button2"
android:textAllCaps="false"
android:layout_alignRight="#+id/linearLayout"
android:layout_alignEnd="#+id/linearLayout"
android:onClick="replaceAwithB"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Attach A"
android:id="#+id/button4"
android:layout_below="#+id/button5"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textAllCaps="false"
android:onClick="attachA"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add B"
android:id="#+id/button5"
android:layout_below="#+id/button"
android:layout_alignRight="#+id/button4"
android:layout_alignEnd="#+id/button4"
android:textAllCaps="false"
android:onClick="addB"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Remove B"
android:id="#+id/button6"
android:layout_alignTop="#+id/button5"
android:layout_toRightOf="#+id/button5"
android:layout_toEndOf="#+id/button5"
android:textAllCaps="false"
android:onClick="removeB"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Replace B with A"
android:id="#+id/button7"
android:layout_alignBaseline="#+id/button6"
android:layout_alignBottom="#+id/button6"
android:layout_toRightOf="#+id/button6"
android:textAllCaps="false"
android:layout_alignRight="#+id/button3"
android:layout_alignEnd="#+id/button3"
android:onClick="replaceBwithA"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Attach B"
android:id="#+id/button8"
android:layout_alignTop="#+id/button4"
android:layout_toRightOf="#+id/button5"
android:layout_toEndOf="#+id/button5"
android:textAllCaps="false"
android:onClick="attachB"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Replace A Only with B"
android:id="#+id/button9"
android:layout_below="#+id/button7"
android:layout_alignLeft="#+id/button7"
android:layout_alignStart="#+id/button7"
android:layout_alignRight="#+id/button3"
android:layout_alignEnd="#+id/button3"
android:textAllCaps="false"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/button4"
android:id="#+id/button11"
android:text="Detached A"
android:textAllCaps="false"
android:onClick="DetachedA"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/button11"
android:layout_below="#id/button8"
android:text="Detached B"
android:textAllCaps="false"
android:onClick="DetachedB"
/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/linearLayout"
android:layout_below="#+id/button11"></LinearLayout>
</RelativeLayout>
fragment_a.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:background="#3498db"
android:layout_weight="1"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Hello Man this is Fragment A"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:textColor="#FFF"
/>
</RelativeLayout>
fragment_b.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:background="#F92"
android:layout_weight="1"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Hello man this is Fragment B"
android:id="#+id/textView2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:textColor="#FFF"
/>
</RelativeLayout>
You can change the fragment with the following way
step 1: Set the id of the layout you want to replace with the other fragment.
fragment xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.neelay.level47.Fragment.Album"
android:background="#4d263238"
android:id="#+id/replace_frag">
<!-- TODO: Update blank fragment layout -->
<Button
android:text="Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:id="#+id/button" />
Step 2: Set the onclick in your fragment and just do the fragment transaction
Fragment java
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_album, container, false);
Button button =(Button)view.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Fragment someFragment = new Replacement();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.replace_frag, someFragment ); // give your fragment container id in first parameter
transaction.addToBackStack(null); // if written, this transaction will be added to backstack
transaction.commit();
}
});
return view;
}
I am replacing the fragment in a scrollable tab and if you want to replace all the scrollable tab then you can set the id of your content_main
I have a Map fragment used in my layout, and the layout is inflated to the class extending Fragment.
So I have 2 fragment now
The Layout
The Mapfragment
On the App launch I launch this fragment, then on Button click I launch another Fragment.
public void launchFragment(Fragment fragment, String tag)
{
// TODO Auto-generated method stub
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_right);
fragmentTransaction.replace(R.id.container, fragment, tag);
fragmentTransaction.addToBackStack(tag);
fragmentTransaction.commit();
}
But on Back press Map fragment crashes.
I have included this code on back press
#Override
public void onBackPressed()
{
// TODO Auto-generated method stub
FragmentManager fm = getSupportFragmentManager();
if (fm.getBackStackEntryCount() > 0)
{
Log.i("MainActivity", "popping backstack");
fm.popBackStack();
}
else
{
Log.i("MainActivity", "nothing on backstack, calling super");
super.onBackPressed();
}
}
Please suggest how to I cope up with this.
I Have attached the screen shot of my full logcat
My XML File
<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="com.winjit.fudtag.BaseAct$PlaceholderFragment" >
<Button
android:id="#+id/xbtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="28dp"
android:background="#drawable/button_bg_orange"
android:text="#string/strTag"
android:textColor="#android:color/white"
android:textStyle="bold" />
<Button
android:id="#+id/xbtnSearchMyJunctn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/xbtnTag"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:background="#drawable/button_bg_green"
android:text="#string/strSearchJunctn"
android:textColor="#android:color/white"
android:textStyle="bold" />
<fragment
android:id="#+id/xmapMyloc"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/xbtnSearchMyJunctn"
android:layout_marginTop="30dp" />
</RelativeLayout>
My requirement is, I've a main activity and I want to display an image and text instead of progress bar in a separate fragment.
I've a separate fragment and I want to display the fragment when user clicks on a button in MainActivity.
My issue is, when I start the app, the fragment gets displayed by default. I want the fragment to be displayed only when user clicks on button. When I start the app I want the activity to be displayed.
I've an activity_main xml as below
<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"
android:background="#drawable/background" >
<ScrollView
android:id="#+id/scrollView"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="10dp"
android:orientation="vertical" >
<TableLayout
android:id="#+id/tableLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:stretchColumns="*" >
<TableRow
android:id="#+id/tableRow1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dip" >
<TextView
android:id="#+id/text1"
style="#style/textForLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dip"
android:text="#string/text1" />
<Spinner
android:id="#+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="20dip"
android:layout_weight="1"
android:drawSelectorOnTop="true"
android:prompt="#string/spinner1"
android:spinnerMode="dialog" >
</Spinner>
</TableRow>
<TableRow
android:id="#+id/tableRow2"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/text2"
style="#style/textForLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dip"
android:text="#string/label2" />
<Spinner
android:id="#+id/spinner2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="20dip"
android:layout_span="6"
android:layout_weight="1"
android:drawSelectorOnTop="true"
android:prompt="#string/spinner2"
android:spinnerMode="dropdown" />
</TableRow>
</TableLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:gravity="center"
android:orientation="horizontal" >
<TextView
android:id="#+id/text3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textColor="#color/red"
android:textSize="#dimen/text_medium"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
</ScrollView>
<fragment
android:id="#+id/progress_bar_fragment"
android:name="com.test.pushnotificationeclipse.ProgressBarFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
The fragemnt_progress_bar.xml is as below:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
style="#style/NoActionBar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/background_all" >
<ImageView
android:id="#+id/imageView_frag_pgbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="#drawable/ic_launcher" />
<TextView
android:id="#+id/text_frag_pgbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/imageView_frag_pgbar"
android:layout_centerHorizontal="true"
android:layout_marginBottom="74dp"
android:textColor="#color/basic_color"
android:textSize="#dimen/text_medium_large" />
</RelativeLayout>
My ProgressBarFragment.java is as below
public class ProgressBarFragment extends Fragment {
#InjectView(R.id.text_frag_pgbar)
TextView textView;
#InjectView(R.id.imageView_frag_pgbar)
ImageView imageView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_progress_bar, container,
false);
ButterKnife.inject(this, view);
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onDetach() {
super.onDetach();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onResume() {
super.onResume();
}
}
My MainActivity.java is as below: When I pass true tohideAndShowFragment(), the fragment should be hidden and when I pass false the fragment should be shown.
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
context = getApplicationContext();
hideAndShowFragment(true);
}
public void hideAndShowFragment(boolean hide) {
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ProgressBarFragment pf = new ProgressBarFragment();
if (hide) {
ft.hide(pf).commit();
} else {
ft.show(pf).commit();
}
}
}
The issue here is your hideAndShowFragment method. You are creating a new instance of ProgressBarFragment, but the FragmentTransaction hide and show methods only work on an attached fragment.
Instead, you should get the fragment you already defined in your XML by id.
public void hideAndShowFragment(boolean hide) {
FragmentManager fm = getFragmentManager();
ProgressBarFragment pf =
(ProgressBarFragment) fm.findFragmentById(R.id.progress_bar_fragment);
FragmentTransaction ft = fm.beginTransaction();
if (hide) {
ft.hide(pf).commit();
} else {
ft.show(pf).commit();
}
}
Additionally, this line is concerning:
context = getApplicationContext();
Your Activity is also a Context object, so unless you need the application specific context for something, you generally want to be using this where you need a context inside your activity.
FragmentManager fm = getFragmentManager();
fm.beginTransaction()
.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out)
.show(yourfragment)
.commit();
Ps:-Dont Don't mess with the visibility flags of the container - FragmentTransaction.hide/show does that internally for you.
Src:- "https://stackoverflow.com/a/16490344/1632286"
You might be better of getting an instance of the fragment in code and using the technique from the official docs as shown below and here (search for 'newInstance'). Add the following static method to your fragment.
public static ProgressFragment newInstance() {
DetailsFragment f = new DetailsFragment();
// Supply args here if needed.
/*Bundle args = new Bundle();
args.putInt("index", index);
f.setArguments(args);*/
return f;
}
Once you have that you can add the fragment to the top view layout with the following fragment transaction code which is inside the button click method.
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction tr = fm.beginTransaction();
tr.add(android.R.id.content, ProgressFragment.newInstance(), "ProgressFragmentTag");
tr.commit();
You can then use the following code to remove the fragment if needed;
FragmentManager fm = getSupportFragmentManager();
ProgressFragment frag = fm.findFragmentByTag("ProgressFragmentTag")
if (frag!=null)
{
FragmentTransaction tr = fm.beginTransaction();
tr.remove(frag).commit();
}
Hope this helps!
I resolved it by adding the fragment instead of having it shown:
public void hideAndShowFragment(boolean hide) {
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ProgressBarFragment pf = (ProgressBarFragment) fm.findFragmentById(R.id.progress_bar_fragment);
if (hide) {
ft.hide(pf).commit();
} else {
ft.add(android.R.id.content, pf, "ProgressFragmentTag").commit();
}
}
int count =1;
if (count == 1) {
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction =
fm.beginTransaction();
fragmentTransaction.replace(R.id.labelframe, new
labelfregaments());
fragmentTransaction.commit();
count =0;
}
else if (count == 0) {
FragmentManager fm = getFragmentManager();
labelfregaments fs = (labelfregaments)fm.findFragmentById(R.id.labelframe);
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.hide(fs);
fragmentTransaction.commit();
count=1;
}
I have used futuresimple's FloatingActionMenu. https://github.com/futuresimple/android-floating-action-button
<com.getbase.floatingactionbutton.FloatingActionsMenu
xmlns:fab="http://schemas.android.com/apk/res-auto"
android:id="#+id/floatingbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layoutDirection="rtl"
android:layout_alignParentBottom="true"
fab:fab_plusIconColor="#color/white"
fab:fab_colorNormal="#0277bd"
fab:fab_colorPressed="#color/pink"/>
Activity code :
add_item_button = (FloatingActionsMenu)findViewById(R.id.floatingbutton);
view = View.inflate(this, R.layout.view_1, null);
add_item_button.addView(view);
add_item_button.canResolveLayoutDirection();
add_item_button.callOnClick();
task = (TextView)view.findViewById(R.id.reminder);
note = (TextView)view.findViewById(R.id.notee);
bday = (TextView)view.findViewById(R.id.bday);
task.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
view.clearFocus();
add_item_button.collapse();
FragmentManager fm = getFragmentManager();
FragmentTransaction ft;
add_task_frag aTF = new add_task_frag();
ft = fm.beginTransaction();
ft.setCustomAnimations(R.anim.slide_up, R.anim.slide_down, R.anim.slide_up, R.anim.slide_down);
ft.addToBackStack("aTF").replace(R.id.MainContent, aTF, "aTF");
ft.commit();
}
});
note.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
view.clearFocus();
add_item_button.collapse();
FragmentManager fm = getFragmentManager();
FragmentTransaction ft;
add_note_frag aNF = new add_note_frag();
ft = fm.beginTransaction();
ft.setCustomAnimations(R.anim.slide_up, R.anim.slide_down, R.anim.slide_up, R.anim.slide_down);
ft.addToBackStack("aNF").replace(R.id.MainContent, aNF, "aNF");
ft.commit();
}
Now, when I click in the floating button, one of the textviews (task, note and bday) gets clicked instead of the button. Any idea whats going on here?
The View i am inflating :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp">
<TextView
android:id="#+id/reminder"
android:padding="5dp"
android:layout_width="wrap_content"
android:textColor="#color/background_floating_material_light"
android:layout_height="wrap_content"
android:text="Add Task"
android:textSize="18dp"
android:background="#drawable/blue_rectangle"/>
<TextView
android:id="#+id/notee"
android:layout_marginTop="10dp"
android:layout_below="#+id/reminder"
android:padding="5dp"
android:layout_width="wrap_content"
android:textColor="#color/background_floating_material_light"
android:layout_height="wrap_content"
android:text="Add Note"
android:textSize="18dp"
android:background="#drawable/blue_rectangle"/>
<TextView
android:layout_marginTop="10dp"
android:layout_below="#+id/notee"
android:id="#+id/bday"
android:padding="5dp"
android:layout_width="wrap_content"
android:textColor="#color/background_floating_material_light"
android:layout_height="wrap_content"
android:text="Add B'day"
android:textSize="18dp"
android:background="#drawable/blue_rectangle"/>
</RelativeLayout>
I want to move from my Custom ListView(which is a ListFragment) to another Fragment by onClick() of a Item. I want to also pass some data which I do by
Fragment f = null;
f = new DescriptionFragment();// it extends Fragment
Bundle args = new Bundle();
args.putString("title", "This is title");
args.putString("desc", "This is Description");
f.setArguments(args);
But Nothing happens using this code.
I tried at my level but now I think that I should use FragmentManager & FragmentTransaction. I tried to implement it by writing
FragmentManager fragmentManager;
android.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.remove(f);
fragmentTransaction.commit();
fragmentManager.executePendingTransactions();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(containerViewId, fragment);// this line gives error & i dont know what to write here
fragmentTransaction.commit();
I think my destination class is fine. It looks like this
public class DescriptionFragment extends Fragment {
public DescriptionFragment(){}
TextView title,desc;
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.description,container,false);
Bundle bundle = this.getArguments();
String stitle = bundle.getString("title");
String sdesc = bundle.getString("desc");
TextView title = (TextView)rootView.findViewById(R.id.textView4);
TextView desc = (TextView)rootView.findViewById(R.id.textView3);
title.setText(stitle);
desc.setText(sdesc);
return rootView;
}
}
Does In description.xml do I have to implement FrameLayout??
However description.xml looks like this
<?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:orientation="vertical"
>
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="120dp"
android:background="#drawable/flagc">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Small Text"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="#+id/textView4"
android:layout_width="match_parent"
android:layout_height="80dp"
android:gravity="center"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
</ScrollView>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/ashokb" >
<ScrollView
android:id="#+id/scrollView2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" >
<TextView
android:id="#+id/textView3"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceMedium"
/>
</ScrollView>
</RelativeLayout>
</LinearLayout>
I hope I made my problem clear
Any help?
Create a Frame Layout in your activity.
Create 2 different Fragment Layouts for each fragment.
When a fragment is called use
transaction.replace(frameLayoutId, fragmentToReplace);
transaction.commit()
Here is a sample for a fragment transition that I am using in my App
public void changeTab(View view) {
int id = view.getId();
if (modelSelected) {
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
InfoFragment info = new InfoFragment();
SettingsFragment settings = new SettingsFragment();
ReportFragment reports = new ReportFragment();
switch (id) {
case R.id.infoTab:
transaction.replace(R.id.loadTabFrag, info);
break;
case R.id.settingsTab:
transaction.replace(R.id.loadTabFrag, settings);
break;
case R.id.reportsTab:
transaction.replace(R.id.loadTabFrag, reports);
break;
default:
break;
}
transaction.commit();
estheticTabHandler(id);
} else {
createSelectModelToast();
}
}
If you want to pass data from one fragment to another you should use a Bundle. In that case you should create a fragment and set its arguments.
Example:
MyFragment myFrag = new MyFragment();
Bundle myBundle = new Bundle();
myBundle.putWhateverData(data); // Where whatever data is the object that you are passing
myFragment.setArguments(myBundle);
And them inside your MyFragment onCreateView() you can use:
Bundle args = this.getArguments();
fragmentTransaction.add(containerViewId, fragment);
in above line where you declare fragment object so it gives error. you remove f fragment but no any valid fragment give so it gives you error.just declare your fragment same as f fragment. thats it...