How to move one fragment to another fragment in android - java

I am developing an app contains fragments. I cannot move one fragment to another fragment.
When i use this code (reference from android value passing from fragment to fragment using recyclerview not working)
SpeedDialFragment fragobj = new SpeedDialFragment();
Bundle bundle=new Bundle();
bundle.putString("message", "From Activity");
fragobj.setArguments(bundle);
switchFragment(R.layout.fragment_page, fragobj);
It is not working.
My codes are shown below.
MainActivity java:
public class MainActivity extends AppCompatActivity implements PageFragment.OnFragmentInteractionListener {
ViewPager viewPage;
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
startService(new Intent(this, LockScreenService.class));
}
private void initView() {
initViewPager();
}
private void initViewPager() {
viewPage = (ViewPager) this.findViewById(R.id.viewpage);
viewPage.setOffscreenPageLimit(3);
viewPage.setCurrentItem(1);
viewPage.setAdapter(new FragmentStatePagerAdapter(getSupportFragmentManager()) {
#Override public Fragment getItem(int position) {
if (position < 2) {
return PageFragment.newInstance("", "");
} else {
return new AmapFragment();
}
}
#Override public int getCount() {
return 3;
}
});
}
#Override public void onFragmentInteraction(Uri uri) {
}
public void loadFragment(int id, Fragment fragment) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(id, fragment, fragment.toString());
ft.addToBackStack(null);
ft.commit();
}
}
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:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.happiness.lockscreen.MainActivity"
>
<android.support.v4.view.ViewPager
android:id="#+id/viewpage"
android:layout_width="match_parent"
android:layout_height="match_parent"
></android.support.v4.view.ViewPager>
</RelativeLayout>
fragment_page.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<Button
android:text="Speed Dial"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/buttonSpeedDial" />
</FrameLayout>
PageFragment.java
public class PageFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
Button button;
Context context;
private OnFragmentInteractionListener mListener;
public PageFragment() {
}
public static PageFragment newInstance(String param1, String param2) {
PageFragment fragment = new PageFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_page, container, false);
button = (Button) view.findViewById(R.id.buttonSpeedDial);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("SpeedDialFragment", "clicked : ");
/*SpeedDialFragment fragment = new SpeedDialFragment(); // replace your custom fragment class
Bundle bundle = new Bundle();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
bundle.putString("key","value"); // use as per your need
fragment.setArguments(bundle);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.replace(viewID,fragment);
fragmentTransaction.commit();*/
SpeedDialFragment fragobj = new SpeedDialFragment();
Bundle bundle=new Bundle();
bundle.putString("message", "From Activity");
fragobj.setArguments(bundle);
switchFragment(R.layout.fragment_page, fragobj);
}
});
return view;
}
public void switchFragment(int id, Fragment fragment) {
if (context == null)
return;
if (context instanceof MainActivity) {
MainActivity mainActivity = (MainActivity) context;
mainActivity.loadFragment(id, fragment);
}
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(
context.toString() + " must implement OnFragmentInteractionListener");
}
}
#Override public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
Please help me.
SpeedDialFragment.java
public class SpeedDialFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public SpeedDialFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment PageFragment.
*/
// TODO: Rename and change types and number of parameters
public static PageFragment newInstance(String param1, String param2) {
PageFragment fragment = new PageFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext=getArguments().getString("message");
Log.d("SpeedDialFragment", "strtext : "+strtext);
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_speeddial, container, false);
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(
context.toString() + " must implement OnFragmentInteractionListener");
}
}
#Override public void onDetach() {
super.onDetach();
mListener = null;
}
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}

if(context==null) return; You have not initialized your context object.
Try this
public void switchFragment(int id, Fragment fragment) {
if (getActivity() instanceof MainActivity) {
MainActivity mainActivity = (MainActivity) getActivity();
mainActivity.loadFragment(id, fragment);
}
}

Related

Work with BroadcastReceiver in many fragments

I working with a PDA that has a laser scanner. For that I'm working with BroadcastReceiver in many fragment. I have one activity that has a BottomNavigationView to switch between three fragments. I'm using BroadcastReceiver like this :
package com.example.package.fragments;
public class MyFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
private final static String SCAN_ACTION = "scan.rcv.message";
ScanDevice sm;
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//Doing my work
}
};
public MyFragment () {
// Required empty public constructor
}
public static MyFragment newInstance(String param1, String param2) {
CarteGriseFragment fragment = new CarteGriseFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
sm = new ScanDevice();
IntentFilter filter = new IntentFilter();
filter.addAction(SCAN_ACTION);
getContext().registerReceiver(mReceiver, filter);
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_carte_grise, container, false);
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onResume() {
super.onResume();
sm = null;
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mReceiver);
}
#Override
public void onPause() {
super.onPause();
sm = null;
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mReceiver);
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
sm = null;
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mReceiver);
}
#Override
public void onDestroy() {
super.onDestroy();
sm = null;
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mReceiver);
}
#Override
public void onDestroyView() {
super.onDestroyView();
sm = null;
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mReceiver);
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
The problem is that, when I move to another fragment, BroadcastReceiver of the first fragment keep working in the second. In fact, when I scan something while being in the second fragment the BroadcastReceiver of the first fragment is called. I searched for many solutions, as you can see in the code above, I tried to unregister the BroadcastReceiver, but not working.
The code of the other fragment is similar to the code above.
I guess the problem is in navigation view all fragments stays in a visible state, hence onPause is not called. you can try to unsubscribe in this method setUserVisibleHint when isVisibleToUser = false
Maybe you can use RxJava.
You say "I have one activity".
Use RxJava like this.
You need to just one BroadcastReceiver in your activity.Listen it when triggered "onReceive" function then you send event with RxJava and listen this event in your fragments.

Android activity fragment listener not working on clicking middle tab in tablayout

I am beginner to android application development. I have implemented a Tablayout in my HomeActivity Layout along with a Viewpager and title to display selected fragment in TextView. The I have placed three Tabitems inside the layout. I was implementing updating Activity title to display on toolbar on clicking a tab button and found a solution this link
activity_home.xml
android.support.design.widget.TabLayout
android:id="#+id/tabLayout"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:tabSelectedTextColor="#color/clinividPink"
app:tabTextAppearance="#style/MineCustomTabText">
<android.support.design.widget.TabItem
android:id="#+id/contactsTabButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:icon="#drawable/contacts_tab_state"
android:text="#string/contacts_tab_name" />
<android.support.design.widget.TabItem
android:id="#+id/casesTabButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:icon="#drawable/cases_tab_state"
android:text="#string/cases_tab_name" />
<android.support.design.widget.TabItem
android:id="#+id/profileTabButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:icon="#drawable/profile_tab_state"
android:text="#string/profile_tab_name" />
</android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:id="#+id/contactsVIew"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toTopOf="#+id/tabLayout"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/toolbar2" />
<TextView
android:id="#+id/home_activity_title"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="12dp"
android:layout_marginBottom="12dp"
android:text="Contacts"
android:textSize="18sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="#+id/toolbar2"
app:layout_constraintEnd_toEndOf="#+id/toolbar2"
app:layout_constraintStart_toStartOf="#+id/toolbar2"
app:layout_constraintTop_toTopOf="#+id/toolbar2" />
The viewpager is filled with the Fragment adapter conditionally with 3 different fragments.
HomeTabLayoutAdapter.java
public class HomeTabLayoutAdapter extends FragmentPagerAdapter {
private Context myContext;
int totalTabs;
private static final String LOG_TAG = HomeTabLayoutAdapter.class.getSimpleName();
public HomeTabLayoutAdapter(FragmentManager fm, Context myContext, int totalTabs) {
super(fm);
this.myContext = myContext;
this.totalTabs = totalTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0: {
Log.d(LOG_TAG, "\nFragment: 0 - Contacts");
ContactsFragment contactsFragment = new ContactsFragment();
return contactsFragment;
}
case 1: {
Log.d(LOG_TAG, "\nFragment: 1 - Cases ");
CasesFragment casesFragment = new CasesFragment();
return casesFragment;
}
case 2: {
Log.d(LOG_TAG, "\nFragment: 2 - Profile");
ProfileFragment profileFragment = new ProfileFragment();
return profileFragment;
}
default: {
Log.d(LOG_TAG, "\nFragment: default");
return new Fragment();
}
}
}
#Override
public int getCount() {
return totalTabs;
}
}
My fragments look something like this
SampleFragment.java
public class CasesFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private static final String LOG_TAG = CasesFragment.class.getSimpleName();
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public CasesFragment() {
// Required empty public constructor
}
public static CasesFragment newInstance(String param1, String param2)
{
CasesFragment fragment = new CasesFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View casesFragmentView = inflater.inflate(R.layout.fragment_cases, container, false);
Log.d(LOG_TAG, "\nCASES listener: " + mListener);
if (mListener != null) {
mListener.onFragmentInteraction("Cases");
}
return casesFragmentView;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
String onHomeAndFragment1Listener(String title); // increment number in name for each fragment interface
}
}
In my HomeActivity.java implements the OnFragmentInteractionListener for all three fragments like this
public class HomeActivity
extends AppCompatActivity
implements ContactsFragment.OnFragmentInteractionListener,
ProfileFragment.OnFragmentInteractionListener,
CasesFragment.OnFragmentInteractionListener
{
TabLayout tabLayout;
ViewPager viewPager;
TextView homeActivityTitleView;
private static final String LOG_TAG = HomeActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
tabLayout=(TabLayout)findViewById(R.id.tabLayout);
viewPager=(ViewPager)findViewById(R.id.contactsVIew);
homeActivityTitleView=(TextView) findViewById(R.id.home_activity_title);
final HomeTabLayoutAdapter adapter = new HomeTabLayoutAdapter(getSupportFragmentManager(), this, tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
Log.d(LOG_TAG, "\nSELECTED tab: " + tab.getPosition());
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
Log.d(LOG_TAG, "\nUNSELECTED tab: " + tab.getPosition());
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
Log.d(LOG_TAG, "\nRESELECTED tab: " + tab.getPosition());
}
});
viewPager.setCurrentItem(1);
}
#Override
public String onHomeAndCasesInteraction(String title) {
Log.d(LOG_TAG, "\nUpdate title: " + title);
homeActivityTitleView.setText(title);
return title;
}
#Override
public String onHomeAndContactsInteraction(String title) {;
Log.d(LOG_TAG, "\nUpdate title: " + title);
homeActivityTitleView.setText(title);
return title;
}
#Override
public String onHomeAndProfileInteraction(String title) {
Log.d(LOG_TAG, "\nUpdate title: " + title);
homeActivityTitleView.setText(title);
return title;
}
#Override
public void onFragmentInteraction(Uri uri) {
}
}
The tablayout UI is working fine but the activity title in my activity_home.xml does not work as expected when I click on the middle tab. it either display the text of the left or right tab depending on the case which was previous tab selected. I have tried to add as much formatting as possible for time being but if you guys need more info, tell me in the comments and I will update.
P.S I have tried experiment with adding a 4th tab and another fragment and the results are even more unpredictable than with 3 tabs. Please someone help me.
UPDATE answer:
Abhisheik's answer works and I changed my tabLayout.addOnTabSelectedListener in my HomeActivity.java as following and removed calls to update title from onCreateView of each fragment.
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
Log.d(LOG_TAG, "\nSELECTED tab: " + tab.getPosition());
viewPager.setCurrentItem(tab.getPosition());
switch (tab.getPosition()) {
case 0: onHomeAndContactsInteraction("Contacts"); return;
case 1: onHomeAndCasesInteraction("Cases"); return;
case 2: onHomeAndProfileInteraction("Profile"); return;
default: onHomeAndCasesInteraction("Cases"); return;
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
Log.d(LOG_TAG, "\nUNSELECTED tab: " + tab.getPosition());
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
Log.d(LOG_TAG, "\nRESELECTED tab: " + tab.getPosition());
}
});
When fragments are used with Tabs, some of the initial tab's fragments are instantiated parallelly.
So invoking the interactionListener's method in onCreateView of fragments won't help.
If you need to know which tab is selected, you can add a listener on tabLayout of your activity
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
//do stuff here
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});

How to maintain fragment state when switching fragments

In my MainActivity class, I have a BottomNavigationView with 3 tabs that switch between activities (home, search, and personal). Whenever I click on any of the tabs, it pulls up the respective fragment, but I believe that I am calling a new fragment each and every time.
I need these fragments to maintain whatever changes are made in them (similarly to how Instagram does). Each fragment is currently very basic (newly created and unchanged), but I want to set them up in a way in which their states are saved when I switch to another fragment and restored when I go back to them.
Below is code for my main activity and the home fragment.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView navigationView = (BottomNavigationView) findViewById(R.id.bottomNavigationView);
navigationView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.content, new HomeFragment()).commit();
}
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener =
new BottomNavigationView.OnNavigationItemSelectedListener(){
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item){
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
switch (item.getItemId()){
case R.id.HomeItem:
transaction.replace(R.id.content, new HomeFragment()).commit();
return true;
case R.id.SearchItem:
transaction.replace(R.id.content, new SearchFragment()).commit();
return true;
case R.id.PersonalItem:
transaction.replace(R.id.content, new PersonalFragment()).commit();
return true;
}
return false;
}
};
}
public class HomeFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public HomeFragment() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static HomeFragment newInstance(String param1, String param2) {
HomeFragment fragment = new HomeFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_home, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
Toast.makeText(context, "Home Fragment Attached", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
You must use transaction.hide(fragment) and transaction.show(fragment) instead of transaction.replace, since replacing will delete the fragment and add it again, removing its saved state.
Doing it my way will call fragments' onPause and onReaume method, not resetting their state.
Hope it helps!

how to intent with on click button from activity to fragment in android studio

how to intent with on click button from activity to fragment in android studio. please anyone tell me what is exact code to intent from activity to fragment with button click on activity.
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button mButNext = (Button) findViewById(R.id.btn_next);
mButNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(this, PropertyListFragment.class);
startActivity(i);
}
});
}
}
PropertyListFragment.class
public class PropertyListFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public static PropertyListFragment newInstance(String param1, String param2) {
PropertyListFragment fragment = new PropertyListFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public PropertyListFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
String strtext = getArguments().getString("pincode");
return inflater.inflate(R.layout.fragment_property_list, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
}
fragment_property_list.xml
<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:orientation="vertical">
<FrameLayout
android:id="#+id/sample_content_fragment"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
Button mButNext = (Button) findViewById(R.id.btn_next);
mButNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
PropertyListFragment plf = PropertyListFragment.newInstance("param1", "param2");
getSupportFragmentManager().beginTransaction().replace(R.id.sample_content_fragment, plf, "tag").commit();
}
});
You use an Intent to open another Activity.
If your goal is to show the Fragment in it's own Activity then create an intent to start the new Activity, and have the target Activity load your Fragment in onCreate. See Adding a Fragment to an Activity
If your goal is to show the Fragment in the same Activity then read slightly further down in the previous link about programmatically add the fragment to an existing ViewGroup

Android - Launch Fragment from Activity

i'm trying to launch a Fragment (a Listview) from an Activity.
The switch should start, when a button is clicked.
My Activity extends from Activity, the Fragment extends ListFragment.
I tried
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
AusgabenFragment ausgabenFragment = new AusgabenFragment();
transaction.replace(R.id.contentFragment, ausgabenFragment);
transaction.commit();
and
Intent intent;
intent = new Intent(getApplicationContext(), AusgabenFragment.class);
startActivity(intent);
The error from the intent try:
Unable to find explicit activity class
I know that I dont have to add Fragments to the AndroidManifest
Thanks for all the suggestions
EDIT: to be launched Fragment Source
public class AusgabenFragment extends ListFragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnAusgabenInteractionListener mListener;
// TODO: Rename and change types of parameters
public static AusgabenFragment newInstance(String param1, String param2) {
AusgabenFragment fragment = new AusgabenFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public AusgabenFragment() {
}
private AusgabenDataSource dataSource;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
dataSource = new AusgabenDataSource(getActivity()); // context mit getActivity
try {
dataSource.open(); // kann Exception werfen daher try catch
} catch (SQLException e) {
e.printStackTrace();
}
List<Ausgaben> AusgabenList = dataSource.getAllAusgaben();
setListAdapter(new ArrayAdapter<Ausgaben>(getActivity(),
android.R.layout.simple_list_item_1, android.R.id.text1, AusgabenList));
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnAusgabenInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Intent intent = new Intent(getActivity(),AusgabenDetailsActivity.class);
String Titel = l.getItemAtPosition(position).toString();
intent.putExtra("value_title",Titel);
getActivity().startActivity(intent);
if (null != mListener) {
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
}
}
public interface OnAusgabenInteractionListener {
// TODO: Update argument type and name
public void onAusgabenInteraction(String id);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnAusgabenInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
This code expects the activity that is hosting the fragment to implement OnAusgabenInteractionListener. It then throws an incorrect exception, to confuse you further.
If you want to use the code, your activity will need to implement OnAusgabenInteractionListener, whatever that is.

Categories

Resources