Open and close fragment from the same button? - android

I have the activity that have fragment. Now I have button that open the fragment. I am wondering how I can use the same button for openning and closing fragment?
My code is:
public class MainActivity extends AppCompatActivity {
FragmentTransaction fTrans;
Button reg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
reg = (Button) findViewById(R.id.reg);
frag1 = new Fragment1();
}
public void openFragment(View v){
fTrans = getFragmentManager().beginTransaction();
fTrans.add(R.id.frgmCont, frag1);
fTrans.commit();
}
}
XML file of MainActivity.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
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.example.user.myapplication5.MainActivity">
<Button
android:id="#+id/reg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Registration"
android:background="#drawable/add_btn"
android:layout_margin="10dp"
android:onClick="openFragment"
/>
<FrameLayout
android:id="#+id/frgmCont"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</LinearLayout>
And here is the fragment:
public class Fragment1 extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment1, null);
}
public void onViewCreated(View view, Bundle savedInstanceState) {
}
}

change your activity code to this
public class MainActivity extends AppCompatActivity {
FragmentTransaction fTrans;
Button reg;
boolean flag = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
reg = (Button) findViewById(R.id.reg);
frag1 = new Fragment1();
}
public void openFragment(View v){
fTrans = getFragmentManager().beginTransaction();
if(flag) {
fTrans.remove(frag1);
} else {
fTrans.add(R.id.frgmCont, frag1);
}
flag = !flag;
fTrans.commit();
}
}

Related

findViewById in different layout (cannot find BottomNavigationView)

I'm doing an app so when you click on a login button, it will then display a screen with a bottom menu. But I'm having problems with setting the listener to the items in the menu. The problem is when I try to use findViewById to find my BottomNavigationView it will look for it in my activity_main instead of the fragment (welcome_fragment) where I have put it, because I only want it to show when someone has logged in. And therefore I will get null as the BottomNavigationView.
I have tried setting setContentView(R.layout.welcome_fragment) in my method "welcomePage", which does make it so that so that it will find it and it won't be null. However this results in a lot of other errors such as
" No view found for id 0x7f080032 (com.example.MyAPP:id/container) for fragment WelcomePage{9547e9f #1 id=0x7f080032}", so I don't believe it to be the right way to go about it.
Here is my MainActivity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fm = getFragmentManager();
Login loggingIn= new Login();
fm.beginTransaction().replace(R.id.container, loggingIn).commit();
}
//When button is pressed we get into this function
public void finishProcess(){
WelcomePage wp = new WelcomePage();
FragmentManager fm = getFragmentManager();
fm.beginTransaction().addToBackStack(null);
fm.beginTransaction().replace(R.id.container, wp).commit();
try {
//Here is where I get null, because we are looking in activity_main
BottomNavigationView bottomNav=findViewById(R.id.bottomnavigate);
bottomNavigation.setOnNavigationItemSelectedListener(menuListener);}
catch (Exception e) {
System.out.println(e);
}
}}
//Have tried this one and it works fine
private BottomNavigationView.OnNavigationItemSelectedListener menuListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {...}
}
Here is my WelcomeFragment:
public class WelcomePage extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.welcome_fragment, container, false)}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
Here is my layout to the welcome_fragment:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".WelcomePage"
android:background="#drawable/welcomegradient">
<FrameLayout
android:id="#+id/showing_page"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/bottomnavigate">
</FrameLayout>
<android.support.design.widget.BottomNavigationView
android:id="#+id/bottomnavigate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
app:menu="#menu/mymenu"
android:background="?android:attr/windowBackground" />
</RelativeLayout>
As I mentioned earlier the problem is that findViewById can't find the BottomNavigationView because it is looking in the activity_main instead of welcome_fragment and I don't want to put my menu in activity_main because I only want to display it when a user has logged in. How do I fix this problem?
Try this, it should work.
WelcomePage
public class WelcomePage extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.welcome_fragment, container, false);
//Have tried this one and it works fine
BottomNavigationView.OnNavigationItemSelectedListener menuListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {...}
BottomNavigationView bottomNav = view.findViewById(R.id.bottomnavigate);
bottomNav.setOnNavigationItemSelectedListener(menuListener);
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
MainActivity
public class MainActivity extends AppCompatActivity {
private FragmentManager fm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fm = getSupportFragmentManager();
Login loggingIn= new Login();
fm.beginTransaction().replace(R.id.container, loggingIn).commit();
}
//When button is pressed we get into this function
public void finishProcess() {
WelcomePage wp = new WelcomePage();
fm.beginTransaction().addToBackStack(null);
fm.beginTransaction().replace(R.id.container, wp).commit();
}
}

Call to Fragment clears app view on startActivity()

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

Launch Launcher Activity when app goes to background

I have 4 activities, when i press home button, it goes in background and when i open it from background, it starts from the activity from where i resume, but i want to open Launcher activity always because in my first activity password is set and i want the user to type password every time when the app is open
android:clearTaskOnLaunch="true"
android:finishOnTaskLaunch="true"
android:launchMode="singleInstance"
`
I have tried this code in Manifest,but it is also not working.
I have also tried this but unfortunately result is same
#Override
protected void onStop() {
sliderShow.stopAutoCycle();
super.onStop();
GalleryBrowserActivity.this.finish();
Log.d("value","value on Stop"+("position"));
}
UPDATE
Hi, I tried to solve this issue so that it can be useful for future too. May be my attempt will not suit in each and every application requirement but it can be helpful in many situations. This is a demo I tried using fragments and I assume this is the only possible way to achieve this requirement. Correct me if I am wrong anywhere. Here is the code:
MainActivity.java
public class MainActivity extends AppCompatActivity {
private Fragment mCurrentFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addFragment(MainFragment.newInstance());
}
public void replaceFragment(Fragment fragment) {
FragmentManager fragmentManager = getSupportFragmentManager();
String backStackTag = fragment.getClass().getName();
boolean fragmentPoped = fragmentManager.popBackStackImmediate(backStackTag, 0);
if (!fragmentPoped) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame, fragment, backStackTag);
if (backStackTag != null) {
fragmentTransaction.addToBackStack(backStackTag);
}
fragmentTransaction.commitAllowingStateLoss();
}
}
public void addFragment(Fragment fragment) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
if (mCurrentFragment != null) {
Fragment f = getSupportFragmentManager().findFragmentByTag(mCurrentFragment.getClass().getName());
if (f != null) {
fragmentTransaction.remove(f);
}
}
fragmentTransaction.add(R.id.frame, fragment, fragment.getClass().getName());
fragmentTransaction.commit();
mCurrentFragment = fragment;
}
public void replaceInMainFragment(Fragment fragment) {
if (mCurrentFragment != null && mCurrentFragment instanceof MainFragment) {
((MainFragment) mCurrentFragment).replaceFragment(fragment);
}
}
}
activity_main.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">
<FrameLayout
android:id="#+id/frame"
android:layout_width="match_parent"
android:layout_height="match_parent"></FrameLayout>
</RelativeLayout>
MainFragment.java
public class MainFragment extends Fragment {
private View mView;
private Fragment mCurrentFragment;
public static MainFragment newInstance() {
MainFragment loginFragment = new MainFragment();
return loginFragment;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.fragment_main, container, false);
Log.e("MainFragment", "onCreateView");
return mView;
}
#Override
public void onStart() {
super.onStart();
Log.e("MainFragment", "onStart");
addFragment(LoginFragment.newInstance());
}
public void replaceFragment(Fragment fragment) {
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
String backStackTag = fragment.getClass().getName();
boolean fragmentPoped = fragmentManager.popBackStackImmediate(backStackTag, 0);
if (!fragmentPoped) {
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame_main, fragment, backStackTag);
if (backStackTag != null) {
fragmentTransaction.addToBackStack(backStackTag);
}
fragmentTransaction.commitAllowingStateLoss();
}
}
public void addFragment(Fragment fragment) {
removeAllFragmentFromBackstack();
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
if (mCurrentFragment != null) {
Fragment f = getActivity().getSupportFragmentManager().findFragmentByTag(mCurrentFragment.getClass().getName());
if (f != null) {
fragmentTransaction.remove(f);
}
}
fragmentTransaction.add(R.id.frame_main, fragment, fragment.getClass().getName());
fragmentTransaction.commit();
mCurrentFragment = fragment;
}
private void removeAllFragmentFromBackstack() {
FragmentManager fm = getActivity().getSupportFragmentManager();
for (int i = 0; i < fm.getBackStackEntryCount(); ++i) {
fm.popBackStack();
}
}
}
fragment_main.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">
<FrameLayout
android:id="#+id/frame_main"
android:layout_width="match_parent"
android:layout_height="match_parent"></FrameLayout>
</RelativeLayout>
LoginFragment.java
public class LoginFragment extends Fragment {
private View mView;
public static LoginFragment newInstance() {
LoginFragment loginFragment = new LoginFragment();
return loginFragment;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.fragment_login, container, false);
Log.e("LoginFragment", "onCreateView");
mView.findViewById(R.id.btnLogin).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((MainActivity) getActivity()).replaceInMainFragment(Fragment1.newInstance());
}
});
return mView;
}
}
fragment_login.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">
<Button
android:id="#+id/btnLogin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Login" />
</RelativeLayout>
Fragment1.java
public class Fragment1 extends Fragment {
private View mView;
public static Fragment1 newInstance() {
Fragment1 fragment1 = new Fragment1();
return fragment1;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.fragment_1, container, false);
mView.findViewById(R.id.btnFrag1).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((MainActivity) getActivity()).replaceInMainFragment(Fragment2.newInstance());
}
});
return mView;
}
}
fragment_1.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">
<Button
android:id="#+id/btnFrag1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="This is Fragment 1" />
</RelativeLayout>
Fragment2.java
public class Fragment2 extends Fragment {
private View mView;
public static Fragment2 newInstance() {
Fragment2 fragment1 = new Fragment2();
return fragment1;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.fragment_2, container, false);
mView.findViewById(R.id.btnFrag2).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
return mView;
}
}
fragment_2.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">
<Button
android:id="#+id/btnFrag2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="This is fragment 2" />
</RelativeLayout>
Hope it helps someone.
OLD
Then I think you need some hack. It will not directly accessible. Try calling 2nd activity when user press back button or any other option to go to the 2nd activity from 3rd activity. Hope it suits your app's requirement.
ThirdActivity.java
public class ThirdActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
}
#Override
public void onBackPressed() {
super.onBackPressed();
startActivity(new Intent(getBaseContext(), SecondActivity.class));
}
}
SecondActivity.java
public class SecondActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
findViewById(R.id.btnJumpToThirdScreen).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getBaseContext(), ThirdActivity.class));
}
});
}
}
OLD
Here is the demo I made just now. For this you need to define android:noHistory="true" in your manifest. Here is the sample code:
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btnJump).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getBaseContext(), SecondActivity.class));
}
});
}
}
SecondActivity.java
public class SecondActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
}
}
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ccc.stackoverflow">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
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=".SecondActivity"
android:noHistory="true"></activity>
</application>
</manifest>
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/btnJump"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="My Launcher Activity Main" />
</RelativeLayout>
Try this demo. Also check removing noHistory flag from your Manifest. You can see the difference. Hope it helps you.
You should change your app design! Users do not want the app restarted every time they step out. They may lose some work.
You should rather use a sign-in dialog, or fragment, that is displayed above the current activity, every time user returns after app goes to background.
If you call the method:
finish();
In your life cycle methods it will work but It will have a disadvantage too:
The advantage is that when the user clicks "back" the activity will be destroyed and the user will have to put the password again.
The disadvantage is that when the user go to another app may be due to a click in the notification. After finishing using that other app, when the user clicks "back" he wont find your activity! He will have to go to a launcher and click your app icon again. This is not good for users for because they will have to click your app from launcher each time they leave the app.
BEST WAY
Declare a boolean in your Activity call it for example:
private boolean hasUserReturned=false;
Then in your onPause() method:
#Override
protected void onPause() {
super.onPause();
hasUserReturned=true;
}
Then in your onResume() nethod:
#Override
protected void onResume() {
super.onResume();
if(hasUserReturned){
recreate();
}
}
This will recreate your activity each time the user revisit your app. It handles "back button" clicks without removing your activity from backstack!
you should just follow life cycle of android,
when user press back button >> onStop() and onDestroy() called
when use press Home button >> onStop() called
when user again back to open application without more waiting and clean from stack(clear background data) >> called onRestart() called
and if user close the application and also remove application from background then it call >> onCreate()
Now just you find your point while following the life cycle of Android :-)
Solution One: apply code in onStop()
Intent intent = new Intent(this, A.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
OR
Solution Two: In AndroidManifest.xml file put android:launchMode="singleTask" in to all Activity
like above
<activity
android:name=".Activity.BookingConfirmClass"
android:label="#string/string_confrim_booking"
android:launchMode="singleTask"
android:parentActivityName=".Activity.HotelDetailsClass"
android:screenOrientation="portrait" />
I could suggest you one approach,
Make all your activities extend from one BaseActivity
Add a variable in BaseActivity
public static boolean HAS_RESUMED_FROM_ACTIVITY=false;
and then override startActivity in your BaseActivity like
#Override
startActivity(Intent intent){
HAS_RESUMED_FROM_ACTIVITY=true;
super.startActivity(intent);
}
Now in onResume of your activities you
#Override
protected void onResume(){
if(!BaseActivity.HAS_RESUMED_FROM_ACTIVITY){
//show your lock screen
}
super.onResume();
}

Fragment wont start - called from Activity

I'm trying to start a fragment from my main activity, but somehow the fragment is not showing up. Can someone help me with this?
Here is my code:
public class Main extends Activity implements OnClickListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b = (Button) findViewById(R.id.action_menu);
b.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v.getId()==R.id.action_menu){
Log.d("--", "menu clicked");
MenuFragment newFragment = new MenuFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(android.R.id.content, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
}
}
main activity layout:
<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:id="#+id/main_rl" >
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="#+id/action_menu" android:text="Menu"/>
</RelativeLayout>
and my fragment Class:
public class MenuFragment extends Fragment{
final String TAG=this.getClass().getSimpleName();
private GridView grid;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View mView;
Log.d(TAG, "Hello from Fragment");
mView=inflater.inflate(R.layout.menu_fullscreen, null);
initWidgets(mView);
return mView;
}
private void initWidgets(View mView) {
grid=(GridView) mView.findViewById(R.id.menu_fullscreen_grid);
}
}
you cannot replace what you put in setContentView(R.layout.main); if main.xml is hardCoded...(xml file). with
transaction.replace...
You may use fragmentActivity without setContentView(R.layout.main)

Accessing Views inside fragment

I'm having troubles accessing the Views that within my Fragment. In the example below, I can't access the 2nd button that is within the Fragment (e.g., findViewById appears to return NULL and the app crashes when I try b2.setText("test") ), but when I directly add it in the activity_main.xml, it does work.
Here is the code:
MainActivity.java
public class MainActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button fragmentButton = (Button)findViewById(R.id.iMainButton);
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.iMainInnerLLContainer, new TestFragment());
ft.commit();
final Button b2 = (Button)findViewById(R.id.iTestFragmentInnerButton);
if(b2 == null) { Log.d("MainActivity.java:", "b2 is null"); }
else { Log.d("MainActivity.java:", "b2 is NOT null"); }
fragmentButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// do stuff here
}
});
}
}
activity_main.xml
<LinearLayout 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:id="#+id/iMainRootLinearLayoutContainer"
android:orientation="vertical"
>
<Button
android:id="#+id/iMainButton"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:text="Add fragment..."
/>
<LinearLayout
android:id="#+id/iMainInnerLLContainer"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="vertical"
>
<!-- Fragment goes here, can reference button if it is added here manually -->
</LinearLayout>
</LinearLayout>
TestFragment.java
public class TestFragment extends Fragment
{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.inflate(R.layout.ltestfragment, container, false);
}
}
ltestfragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/iTestFragmentOuterLinearLayout"
>
<Button
android:id="#+id/iTestFragmentInnerButton"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:text="This is my test fragment button."
/>
</LinearLayout>
I think I'm missing something very basic here and I would appreciate some insight on what that might be.
Thank you in advance!
I think you need to set up a textchangelistener in your fragment.
public class FragmentA extends Fragment {
TextChangeListener listener;
public interface TextChangeListener {
public void onTextChange(CharSequence newText);
}
public void setTextChangeListener(TextChangeListener listener) {
this.listener = listener;
}
Then, in your activity, set up the listener :
public class ActivityAB extends FragmentActivity {
FragmentA fragmentA;
FragmentB fragmentB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ab);
FragmentManager manager = getSupportFragmentManager();
fragmentA = (FragmentA) manager.findFragmentById(R.id.fragmentA);
fragmentB = (FragmentB) manager.findFragmentById(R.id.fragmentB);
fragmentA.setTextChangeListener(new TextChangeListener() {
#Override
public void onTextChange(CharSequence newText) {
fragmentB.updateTextValue(newText);
}
});
}
}
Implement an interface to listen to the events of a fragment from its activity.
Code in Fragment:-
public class TestFragment extends Fragment
{
public interface OnClickListener
{
public void onButtonClicked(<data type><data>);
}
b2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
listener.onButtonClicked(<<pass some values here>>);
}
});
}
Code in Main:-
MainActivity extends FragmentActivity implements TestFragment.OnClickListener,
{
#Override
public void onButtonClicked(<<receive the pased data here>>) {
//do some stuff here with the received data after the button is clicked
}
}

Categories

Resources