Trying to learn fragments, why fragment is not showing up - android

Here is the xml for my main layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<FrameLayout
android:id="#+id/fragment_placeholder"
android:layout_width="250dp"
android:layout_height="0dip"
android:layout_weight="1" >
<ImageView
android:contentDescription="image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher" />
</FrameLayout>
</LinearLayout>
Code for fragment class
public class ExerciseFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.fragment_layout, container, false);
return view;
}
}
and code in main activity for showing fragment on click of a button:
ExerciseFragment fragment = new ExerciseFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragment_placeholder, fragment);
ft.commit();
if (fragment.isVisible()) {
Toast.makeText(this, "works", Toast.LENGTH_LONG).show();
} else
Toast.makeText(this, "nooooo", Toast.LENGTH_LONG).show();
The toast says "noooo" meaning the fragment is not visible, and it still shows an image which i set up in the framelayout holder which i want to replace. Any ideas why the fragment is not showing up?
EDIT: COMPLETE CODE FOR MAIN ACTIVITY
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getActionBar().setDisplayHomeAsUpEnabled(false);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.workout_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_exercise:
ExerciseFragment fragment = new ExerciseFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragment_placeholder, fragment);
ft.commit();
if (fragment.isVisible()) {
Toast.makeText(this, "works", Toast.LENGTH_LONG).show();
} else
Toast.makeText(this, "nooooo", Toast.LENGTH_LONG).show();
break;
}
return super.onOptionsItemSelected(item);
}
}

Instead of using ft.replace(R.id.fragment_placeholder, fragment);, try using ft.add(R.id.fragment_placeholder, fragment);. Since the R.id.fragment_placeholder doesn't contain a fragment yet, you aren't replacing anything, you are merely adding on to the layout. The .add(int containerViewId, Fragment fragment) function should work for your case. In the future, if you are going to change the fragment contained in R.id.fragment_placeholder, use .replace(int containerViewId, Fragment fragment).
Hope this works!

Related

How to toggle between fragments

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
);
}
}

start fragment on actionbar icon click

I want to open a fragment when an activity's actionbar icon is clicked and remove the fragment (and go back to activity) when back button (in fragment's layout) is clicked. The imp thing is there is no <fragment> in my activity layout.
main activity layout
<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:gravity="center"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is main activity layout"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
MainActivity
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main_actions, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.settings:
newintent();
default:
break;
}
return true;
}
private void newintent() {
// Do something here to open FragmentOne.class
}
}
create a fragment and add this code in your click event method
private Fragment newFragment=new NewFragment();//global variable
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.popBackStack();
FragmentTransaction ft =fragmentManager.beginTransaction();
ft.replace(R.id.current_layout, newFragment,"Order");
ft.commit();
you can follow this link .. click

java.lang.IllegalArgumentException: No view found for

What I am trying to do: Starting from a Master/Detail flow project, I am trying to enable the user to press an item in the ActionMenu which should show a fragment where new data can be put in.
Problem: I get an error when I try to start the fragment. What am I doing wrong?
After pasting the code I think I have made a mess of it. Still need help.
Error:
java.lang.IllegalArgumentException: No view found for id 0x7f090040 (com.example.androidtest:id/AddItem_fragment) for fragment AddItem{5b161e7 #1 id=0x7f090040}
ItemListActivity.java:
public class ItemListActivity extends ActionBarActivity implements
ItemListFragment.Callbacks {
private boolean mTwoPane;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_list);
if (findViewById(R.id.item_detail_container) != null) {
mTwoPane = true;
((ItemListFragment) getSupportFragmentManager().findFragmentById(
R.id.item_list)).setActivateOnItemClick(true);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_actions, menu);
setTitle("Shoppinglistan");
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_add:
openAddItem();
return true;
case R.id.action_send:
//openSettings();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onItemSelected(String id) {
if (mTwoPane) {
Bundle arguments = new Bundle();
arguments.putString(ItemDetailFragment.ARG_ITEM_ID, id);
ItemDetailFragment fragment = new ItemDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.item_detail_container, fragment).commit();
} else {
Intent detailIntent = new Intent(this, ItemDetailActivity.class);
detailIntent.putExtra(ItemDetailFragment.ARG_ITEM_ID, id);
startActivity(detailIntent);
}
}
public void openAddItem() {
AddItem additem = new AddItem();
getSupportFragmentManager().beginTransaction()
.add(R.id.AddItem_fragment, additem).commit();
}
public static class AddItem extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.additem_layout,
container, false);
return rootView;
}
}
}
activity_item_detail.xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/item_detail_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.androidtest.ItemDetailActivity"
tools:ignore="MergeRootFrame" >
<fragment
android:name="com.example.androidtest.AddItem"
android:id="#+id/AddItem_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
/>
</FrameLayout>
additem_layout:
<?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" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
your problem is this line
public void openAddItem() {
AddItem additem = new AddItem();
getSupportFragmentManager().beginTransaction()
.add(R.id.AddItem_fragment, additem).commit();
}
you already have it here
<fragment
android:name="com.example.androidtest.AddItem"
android:id="#+id/AddItem_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
/>
you can not recreate it programmatically, all you need to do is remove the programmatically added fragment,and this will be there, since (in a different language its stack)..
EDIT
to address your comment,first of all add a tag to your fragments when calling ItemDetailFragment for instance "ItemDetailFragment" & instead of the previous code in openAddItem() replace them with this
public void openAddItem() {
getSupportFragmentManager().beginTransaction().remove(getSupportFragmentManager().
findFragmentByTag("ItemDetailFragment"));
getSupportFragmentManager().popBackStackImmediate(); //
// if your fragment is still not showing then uncomment the below line
//getSupportFragmentManager().beginTransaction().show(getSupportFragmentManager().
findFragmentById(the_id_of_ur_fragment));
}
hope its good enough
From the documentation, the add method:
abstract FragmentTransaction add(int containerViewId, Fragment fragment)
Calls add(int, Fragment, String) with a null tag.
In your code:
public void openAddItem() {
AddItem additem = new AddItem();
getSupportFragmentManager().beginTransaction().add(R.id.AddItem_fragment, additem).commit();
}
This code will find in your views a view with the id R.id.AddItem_frament and it will try to attach to it the view associated to the fragment passed. Since in your layout there is not a ViewGroup that serves as a container it is launching you a legitimate IllegalArgumentException since the id is not present. What you have to do is provide a container in which you can add all the fragments and passing to the add method of the transaction this id.

Change Fragment dynamic

I have 2 questions. First, can me say someone, why this not works? I just try to change the fragment, but he does nothing. I just see the first fragment.
mainActivity:
...
if (savedInstanceState == null) {
fm.beginTransaction()
.add(R.id.firstFragment, new firstFragment()).commit();
}
findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
switchFragment(R.id.firstFragment, new firstFragment());
}
});
findViewById(R.id.button2).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
switchFragment(R.id.secondFragment, new secondFragment());
}
});
}
private void switchFragment(int fragId, Fragment frag){
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(fragId, frag);
ft.commit();
}
Fragments like this in the main.xml:
<Fragment
android:id="#+id/firstFragment"
android:name="com.example.firstFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/View01"
android:layout_below="#+id/view1" />
Fragmentclass just have this:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_clublist, container, false);
return view;
}
And a Fragment just look like this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fragment1"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#FFFF0000"/>
I don't know, why he does not change the fragment. A check, that switchFragment really calling is true.
Second question is: Is this a good way to change fragments? What is, if i have 10 fragments?
Thanks for your help! :)
int fragId
should be the id of the container that hosts the Fragment, not the id of the fragment itself

Action Bar Tabs: How do I pass arguments when using a single fragment instantiated more than once

I want to include Action Bar Tabs in my application and am working through a tutorial example to get my head round it all.
The tutorial has two tabs each with their own fragment so then when the tab is selected the correct fragment is shown...this seems to be the approach shown in all the examples I can find.
What I want to do however is to have each tab have their own instantiation of the Same fragment and to pass an argument to the Fragment so that the code can behave differently dependent on which tab is selected.
This is the code from the tutorial:
ACTIVITY (Start Activity)
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
appContext = getApplicationContext();
//ActionBar
ActionBar actionbar = getActionBar();
actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab PlayerTab = actionbar.newTab().setText("Fragment A");
ActionBar.Tab StationsTab = actionbar.newTab().setText("Fragment B");
Fragment PlayerFragment = new AFragment();
Fragment StationsFragment = new BFragment();
PlayerTab.setTabListener(new MyTabsListener(PlayerFragment));
StationsTab.setTabListener(new MyTabsListener(StationsFragment));
actionbar.addTab(PlayerTab);
actionbar.addTab(StationsTab);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.menuitem_search:
Toast.makeText(appContext, "search", Toast.LENGTH_SHORT).show();
return true;
case R.id.menuitem_add:
Toast.makeText(appContext, "add", Toast.LENGTH_SHORT).show();
return true;
case R.id.menuitem_share:
Toast.makeText(appContext, "share", Toast.LENGTH_SHORT).show();
return true;
case R.id.menuitem_feedback:
Toast.makeText(appContext, "feedback", Toast.LENGTH_SHORT).show();
return true;
case R.id.menuitem_about:
Toast.makeText(appContext, "about", Toast.LENGTH_SHORT).show();
return true;
case R.id.menuitem_quit:
Toast.makeText(appContext, "quit", Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("tab", getActionBar().getSelectedNavigationIndex());
}
}
The following class is included at the end in the same java file :
class MyTabsListener implements ActionBar.TabListener {
public Fragment fragment;
public MyTabsListener(Fragment fragment) {
this.fragment = fragment;
}
public void onTabReselected(ActionBar.Tab tab, android.app.FragmentTransaction ft) {
Toast.makeText(StartActivity.appContext, "Reselected!", Toast.LENGTH_LONG).show();
}
public void onTabSelected(ActionBar.Tab tab, android.app.FragmentTransaction ft) {
ft.replace(R.id.fragment_container, fragment);
}
public void onTabUnselected(ActionBar.Tab tab, android.app.FragmentTransaction ft) {
ft.remove(fragment);
}
This is A FRAGMENT:
public class AFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.afragment, container, false);
}
}
This is B FRAGMENT
public class BFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.bfragment, container, false);
}
}
HERE ARE THE XML FILES:
Main.xml
<LinearLayout
android:orientation="vertical"
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" >
A Fragment:-
<?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" >
<TextView android:id="#+id/textView1"
android:text="Fragment A"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
B Fragment:
<?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" >
<TextView android:id="#+id/textView2"
android:text="Fragment B"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
So what I would like to do would be to get rid of Fragment B completely and have both Station and Player tabs use Fragment A. Then within Fragment A put code that did one thing if it is for Station and something else if it is for Player. I've tried all sorts with trying to put an Args Bundle but I'm new to this and nothing I have tried has worked,
I now have a solution that works here.
The way that I have done it is to set a Tag on each of the Tabs as I set them up and then get the current Tab in my fragment and use it's tag.
Code changes are as follows:
In Activity, so that I am just using Fragment A:-
ActionBar.Tab PlayerTab = actionbar.newTab().setText("Tab A")
.setTag("A");
ActionBar.Tab StationsTab = actionbar.newTab().setText("Tab B")
.setTag("B");
Fragment PlayerFragment = new AFragment();
Fragment StationsFragment = new AFragment();
Now within Fragment A I have overriden onResume() and put in the following code :-
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
TextView v = (TextView)getView().findViewById(R.id.textView1);
Tab b = getActivity().getActionBar().getSelectedTab();
String c = b.getTag().toString();
if (c.equals("A"))
v.setText("Tab A has been selected");
if (c.equals("B"))
v.setText("It's Tab B now");
}

Categories

Resources