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)
Related
I have an app that has 1 Main Activity and 5 main fragments. When the MainActivity is created I create a List containing each of the 5 fragments. The user is presented with a tab bar on the bottom of the screen which he/she can use to navigate between fragments. How do I set this up so as when the user selects a tab, the corresponding fragment is shown without creating a new instance of it? Just want to change the view on the screen to the already created fragment.
I am using a BottomBar from https://github.com/roughike/BottomBar which calls a "onTabSelected" interface method when a tab is pressed.
You can use 5 Fragments with the library you specified like this. The layout file should look like this
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<!-- This could be your fragment container, or something -->
<FrameLayout
android:id="#+id/contentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/bottomBar" />
<com.roughike.bottombar.BottomBar
android:id="#+id/bottomBar"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_alignParentBottom="true"
app:bb_tabXmlResource="#xml/bottombar_tabs" />
</RelativeLayout>
The containing Activity class will replace the Framelayout with Fragment depending on the Fragment selected from the BottomBar View. A simple example
public class Main3Activity extends AppCompatActivity {
private Fragment fragment;
private FragmentManager fragmentManager;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_three_tabs);
BottomBar bottomBar = (BottomBar) findViewById(R.id.bottomBar);
bottomBar.setOnTabSelectListener(new OnTabSelectListener() {
#Override
public void onTabSelected(#IdRes int tabId) {
if(tabId == R.id.tab_home){
fragment = new HomeFragment();
}
if(tabId == R.id.tab_favorite){
fragment = new FavoriteFragment();
}
}
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.contentContainer, fragment).commit();
});
bottomBar.setOnTabReselectListener(new OnTabReselectListener() {
#Override
public void onTabReSelected(#IdRes int tabId) {
Toast.makeText(getApplicationContext(), TabMessage.get(tabId, true), Toast.LENGTH_LONG).show();
}
});
}
}
Then you can create individual Fragment with their content like below
public class FavoriteFragment extends Fragment {
public FavoriteFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_favorite, container, false
);
}
}
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();
}
}
I am new to android. I want a EditText such that it should be visible to all activities & if I change its contents in any activity, they should reflect in every activity.Please give me solution...!!!
This can be done using a fragment , fragments are reusable , and can be attached to multiple activities , there is a single xml and java file for a fragment, when you make changes of EditText in these files , changes will be made in all of your activities , So make a fragment and attach it to all of your Activities.
If you want to use all activities, you can create a static variable
public class Utils {
public static String myString;
}
And before you start another activity, you can set the variable
Utils.myString = editText.getText().toString();
Then onResume of each activity, you can get the variable and set it to EditText
#Override
protected void onResume() {
super.onResume();
editText.post(new Runnable() {
#Override
public void run() {
if (editText!= null) {
editText.setText(Utils.myString);
}
}
});
}
But i recommend that you should use fragment is this case. It's easier.
Reuse the same fragment across the different activities.
The assumption here is that you want the edit text to be shown in activity 1 and 2.
Activity1 will be called before Activity2.
the layout of both activity1 and activity2 have a framelayout of id holder
Activity1
public class Activity1 extends Activity{
public static Fragment editTextFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_group);
...
editTextFragment = new EditTextFragment();
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.holder, editTextFragment);
ft.commit()
}
}
Activity2
public class Activity2 extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_group);
...
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.holder, Activity1.editTextFragment);
ft.commit()
}
}
EditTextFragment.java
public class EditTextFragment extends Fragment {
public testFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_edittext, container, false);
}
}
layout/fragment_edittext.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"
tools:context="com.example.editTextFragment">
<EditText
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
I have aŃivity with one button and frame:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="new fragment"
android:id="#+id/replaceFragment" android:layout_gravity="center_horizontal"/>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="fill_parent" android:layout_gravity="center_horizontal" android:id="#+id/contentFrame">
</FrameLayout>
</LinearLayout>
code:
public class MyActivity extends Activity implements View.OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button replaceBtn = (Button) findViewById(R.id.replaceFragment);
replaceBtn.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.replaceFragment:
Fragment fragment1 = new Frag1();
FragmentTransaction fTrans = getFragmentManager().beginTransaction();
fTrans.replace(R.id.contentFrame, fragment1);
fTrans.commit();
break;
}
}
}
button is pressed, etc. I create a fragment:
public class Frag1 extends Fragment implements View.OnClickListener {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.frag1, null);
Button replaceBtn2 = (Button) v.findViewById(R.id.replaceFragment2);
replaceBtn2.setOnClickListener(this);
return v;
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.replaceFragment2:
Frag2 fragment2 = new Frag2();
FragmentTransaction fTrans = getFragmentManager().beginTransaction();
fTrans.replace(R.id.contentFrame,fragment2);
fTrans.commit();
break;
}
}
}
it also has a button which when pressed I create fragment2:
public class Frag2 extends Fragment implements View.OnClickListener {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.frag2, null);
Button replaceBtn3 = (Button) v.findViewById(R.id.replaceFragment3);
replaceBtn3.setOnClickListener(this);
return v;
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.replaceFragment3:
Frag3 fragment3 = new Frag3();
FragmentTransaction fTrans = getFragmentManager().beginTransaction();
fTrans.replace(R.id.contentFrame,fragment3);
fTrans.commit();
break;
}
}
}
fragment2 also creates a new fragment3:
public class Frag3 extends Fragment{
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.frag3, null);
return v;
}
}
if I do when creating each fragment will add a line:
fTrans.addToBackStack(null);
then later when I press the "back" button on the screen will appear the fragments in reverse order. but I want to when I'm in fragmente3 when you press the "back" appears immediately fragment1.
if I do not add the line fTrans.addToBackStack(null); in fragment2 they overlap.
in order to do that, you can keep the fragments backStack references in your activity or for example onBackPressed you could try something like below:
if (getSupportFragmentManager().getBackStackEntryCount() != 0) {
//back to fragment 1.
}
Here you are a function which I use for one of my projects. I implemented it in the parent of the Activity that manages the fragments. I don't know if I'm going to clarify anything about the behaviour because all you tell us in you question make sense to me.
I my case, it was a simple app (almost static), but it changes fragments and, as you want to, many times I want to go back two fragment in "history" so I think it could help.
#Override
public void replaceFragment(FRAGMENT_TYPE destinyFragmentType, int fragmentContainerID, boolean addToBackStack) {
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
Fragment currentFragment = FragmentFactory.getFragment(destinyFragmentType);
fragmentTransaction.replace(fragmentContainerID, currentFragment);
if (addToBackStack) {
fragmentTransaction.addToBackStack(null);
}
fragmentTransaction.commit();
}
Notes:
The second parameter is the parameter that indicates if you want to
keep in history or not. For your case: frg1 -> fr2 : param true; fr2
-> fr3 : param false;
I used a Factory in order to get a cleaner code, but you can use
whatever you want, change the header, give the function your fragment
etc.
I hope this helps!!
I'm trying do understand the lifecycle of Fragment.
I have a MainActivity, with a layout including two FrameLayout to load Fragments, one for a top bar with a vertical menu, another one for the content.
When I start the app, an instance of HomeFragment is loaded in the content FrameLayout container. Then when I click on a button in the menu, an instance of SomeFragment replaces it.
When on the SomeFragment content, I click on the device's Home button, and all the visible Fragment (i.e. the TopBarFragment and the SomeFragment) are destroyed and detached from the MainActivity, i.e. onDestroyView, onDestroy and onDetach are called for both.
Now when I restart the app, the TopBarFragment and the SomeFragment are created and destroyed (full lifecycle from onAttach to onDetach) and then the TopBarFragment and the HomeFragment are created, as expected from the code in the MainActivity's onCreate.
Why are the TopBarFragment and the SomeFragment, i.e. the latest visible Fragment before clicking on the device's Home button, recreated and destroyed before executing what's in the MainActivity's onCreate?
Note: in order to test my app I checked the option Don't keep activities in my device's developer options.
MainActivity.java
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
Fragment homeFragment = new HomeFragment();
fragmentTransaction.replace(R.id.content_container, homeFragment, "");
Fragment topBarFragment = new TopBarFragment();
fragmentTransaction.replace(R.id.top_bar_container, topBarFragment, "top_bar_fragment");
fragmentTransaction.commit();
}
}
main.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" >
<FrameLayout
android:id="#+id/content_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="44dp" />
<FrameLayout
android:id="#+id/top_bar_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipChildren="false" />
</RelativeLayout>
TopBarFragment.java
public class TopBarFragment extends Fragment{
private int mSelectedMenuOption = 0;
private LinearLayout mVerticalMenu;
private Boolean mMenuIsOpen = true;
private ImageButton btn_01, btn_02; // there are more
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.top_bar, container, false);
}
#Override
public void onActivityCreated (Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
btn_01 = (ImageButton) getView().findViewById(R.id.btn_01);
btn_02 = (ImageButton) getView().findViewById(R.id.btn_02);
btn_01.setOnClickListener(mButtonClickListener);
btn_02.setOnClickListener(mButtonClickListener);
mVerticalMenu = (LinearLayout) getView().findViewById(R.id.vertical_menu);
toggleMenu(0);
Button btn_menu = (Button) getView().findViewById(R.id.btn_menu);
btn_menu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// toggle vertical menu
}
});
}
private OnClickListener mButtonClickListener = new OnClickListener()
{
#Override
public void onClick(View v) {
/* ... */
if(!v.isSelected()){
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
switch(v.getId()){
case R.id.btn_01:
Fragment homeFragment = new HomeFragment();
fragmentTransaction.replace(R.id.content_container,homeFragment, "");
fragmentTransaction.commit();
break;
case R.id.btn_02:
Fragment someFragment = new SomeFragment();
fragmentTransaction.replace(R.id.content_container, someFragment, "");
fragmentTransaction.commit();
break;
}
}
}
};
}
SomeFragment
public class SomeFragment extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
((TopBarFragment)getActivity().getSupportFragmentManager().findFragmentByTag("top_bar_fragment")).setSelectedButton(1);
return inflater.inflate(R.layout.some_fragment, container, false);
}
}