start fragment on actionbar icon click - android

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

Related

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.

Issues in using new Toolbar component,hiding and showing Navigation drawer icon ,Home Up icon click event from fragments

I recently started updating my app to use the new Toolbar component introduced in Android 5.0 with navigation drawer. Flow of app is : MainActivity which has a toolbar, navigation drawer with menu 1. Home 2. Cart.
Home Menu navigates to "Home Detail" through a button in it.
Layout of "MainActivity" :
<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:orientation="vertical">
<include
android:id="#+id/toolbar"
layout="#layout/toolbar" />
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<FrameLayout android:id="#+id/activity_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<ListView
android:id="#+id/left_drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#android:color/white"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:listSelector="#android:color/transparent" />
</android.support.v4.widget.DrawerLayout>
I am adding two fragments HomeFragment,CartFragment on "MainActivity" on menu selected from drawer as below, default selection is position 0 i.e "Home"
class "MainActivity.java" ::
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
drawer = (DrawerLayout) findViewById(R.id.drawer);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
tvTitle = (TextView) mToolbar.findViewById(R.id.toolbar_title);
if (mToolbar != null) {
setSupportActionBar(mToolbar);
}
mDrawerToggle = new ActionBarDrawerToggle(this, drawer,mToolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) {
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitle);
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mDrawerTitle);
}
};
drawer.setDrawerListener(mDrawerToggle);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
dataList = new ArrayList<DrawerItem>();
dataList.add(new DrawerItem(Constants.V_HOME, R.drawable.ic_launcher));
dataList.add(new DrawerItem(Constants.V_MY_CART, R.drawable.ic_launcher));
mDrawerList.setAdapter(adapterDrawer);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// to show first "Home fragment" on start up of application
if(savedInstanceState==null)
SelectItem(0);
}
public void SelectItem(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = new HomeFragment();
replaceFragment(fragment, Constants.V_TAG_HOME,false,"Home");
break;
case 1:
fragment = new CartFragment();
replaceFragment(fragment, Constants.V_TAG_MY_CART,false,"My Cart");
break;
}
drawer.closeDrawer(mDrawerList);
}
public void replaceFragment(Fragment fragment,String fragment_tag,boolean showHome,String title){
frgManager = this.getSupportFragmentManager();
FragmentTransaction ft = frgManager.beginTransaction();
ft.replace(R.id.activity_frame,fragment,fragment_tag);
if(showHome)
ft.addToBackStack(null);
ft.commit();
shouldDisplayHomeUp(showHome);
}
public void shouldDisplayHomeUp(boolean showHome){
if(showHome){
mDrawerToggle.setDrawerIndicatorEnabled(false);
drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}else{
mDrawerToggle.setDrawerIndicatorEnabled(true);
drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setHomeButtonEnabled(false);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId())
{
case android.R.id.home:
Toast.makeText(getApplicationContext(),"main act clicked", Toast.LENGTH_SHORT).show();
return false;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
if(frgManager.getBackStackEntryCount()>0){
getSupportFragmentManager().popBackStack();
// show the drawer icon when on moving back
shouldDisplayHomeUp(false);
}else{
super.onBackPressed();
}
mDrawerToggle.syncState();
}
My home fragment has button "Detail" on click of button,replaces to other fragment :"HomeDetailFragment"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/btnDetail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Home detail" />
<FrameLayout
android:id="#+id/home_frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
class "HomeFragment.java" btnDetail click event which replace to other fragment "HomeDetailFragment"::
btnDetail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Fragment fragment = new HomeDetailFragment();
((MainActivity)getActivity()).showDrawerIndicator(false);
FragmentManager frManager = getActivity().getSupportFragmentManager();
FragmentTransaction ft = frManager.beginTransaction();
ft.addToBackStack(null);
ft.replace(R.id.activity_frame, fragment).commit();
}
});
class "HomeDetailFragment.java" ::
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
// update the actionbar to show the up carat/affordance
((MainActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// your code for order here
Toast.makeText(getActivity(), "home detail", Toast.LENGTH_LONG).show();
((MainActivity)getActivity()).onBackPressed();
return true;
}
return true;
}
My problems ::
1. In "HomeDetailFragment", I can see the "UP home icon" but cannot get the click event of home icon onOptionsItemSelected not being called, so cant navigate back to HomeFragment
2. When pressing the Phone Back Button, and again navigating to "Home Detail" it is not showing "UP home icon"
Please guide me.
In "HomeDetailFragment", I can see the "UP home icon" but cannot get the click event of home icon onOptionsItemSelected not being called, so cant navigate back to HomeFragment
One way to achieve this is by using the Toolbar from your MainActivity like so:
Toolbar mToolbar= ((MainActivity)getActivity()).mToolbar;
mToolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_nav_back));
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("MrE", "home selected");
}
});
When pressing the Phone Back Button, and again navigating to "Home Detail" it is not showing "UP home icon"
The reason your code isn't getting called is because it is in the onCreate of your Fragment. Move it to the onCreateOptionsMenu instead to have it update.
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Put toolbar stuff from above here
super.onCreateOptionsMenu(menu, inflater);
}
I had the exact issue.
Use the setToolbarNavigationClickListener method.
In MainActivity.java,
actionBarToggle.setToolbarNavigationClickListener(new View.OnClickListener({
#Override
public void onClick(View v) {
MainActivity.this.onSupportNavigateUp();
}
});
Avoid implementing Up Navigation individually in Fragments.
You called getSupportActionBar().setDisplayHomeAsUpEnabled(true) which shows the button in the toolbar but doesn't activate it.
Calling getSupportActionBar().setHomeButtonEnabled(true); in addition should do the job.
You show the back-button in the toolbar from within the Fragment which is something I would avoid. Try moving this part to your Activity, when you do the FragmentTransaction.

Attaching Fragments to Activities

I created two activities and used intents to switch from first activity to second. Also I used fragments in the second activity. When I tried to run the app,the app gets started and it stops unfortunately. When I remove fragments from my app, the app runs. What should I do to get rid of this error? This is my code...
First Activity code
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b=(Button)findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i=new Intent(MainActivity.this,FirstActivity.class);
startActivity(i);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Second Activity code
public class FirstActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
public void selectFrag(View view)
{
Fragment fr;
if(view == findViewById(R.id.button2))
{
fr = new FragmentOne();
}
else if(view==findViewById(R.id.button3)){
fr = new FragmentOne();
}
else
{
fr=new FragmentOne();
}
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.fragment_first, fr);
fragmentTransaction.commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.first, menu);
return true;
}
}
Fragment code
public class FragmentOne extends Fragment {
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
//Inflate the layout for this fragment
return inflater.inflate(
R.layout.fragment_one, container, false);
}
}
Manifest of Second Activity in which I tried to use fragments
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".FirstActivity" >
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/button2"
android:layout_alignParentBottom="true"
android:layout_alignRight="#+id/button2"
android:layout_marginBottom="66dp"
android:text="#string/IDE" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/button3"
android:layout_alignLeft="#+id/button1"
android:layout_marginBottom="42dp"
android:layout_toLeftOf="#+id/fragment_first"
android:text="#string/Applications" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/fragment_first"
android:layout_alignBottom="#+id/fragment_first"
android:layout_alignParentLeft="true"
android:layout_marginLeft="18dp"
android:text="#string/Operating_Systems" />
<fragment
android:id="#+id/fragment_first"
android:name="com.example.test"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/button3"
android:layout_alignParentTop="true"
android:layout_marginTop="56dp"
android:layout_toRightOf="#+id/button1" />
You are trying to replace a static Fragment. Static Fragments (ones defined in xml) cannot be manipulated via FragmentTransactions.
Also, you are telling Android to inflate a Fragment called com.example.test here:
<fragment
android:id="#+id/fragment_first"
android:name="com.example.test"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/button3"
android:layout_alignParentTop="true"
android:layout_marginTop="56dp"
android:layout_toRightOf="#+id/button1" />
First, create a container in your FirstActivity's layout
Secondly, using the fragment manager, set FragmentOne to it
That is pretty much all you need to get this working!

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

Trying to learn fragments, why fragment is not showing up

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!

Categories

Resources