Fill listview from fragment - android

I have a layout file containing a listview that I would like to fill with the help of a Fragment. But it continues to give me errors.
The layout file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true" >
</ListView>
<TableLayout
android:id="#+id/details"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:stretchColumns="1" >
<Button
android:id="#+id/create_patient_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/create_patient_button" />
</TableLayout>
</RelativeLayout>
My fragmentActivity:
public class BasicFragmentActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_patient_view);
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.list);
if (fragment == null) {
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.list, new BasicFragment());
ft.commit(); // Make sure you call commit or your Fragment will not be added.
// This is very common mistake when working with Fragments!
}
}
}
My ListFragment:
public class BasicFragment extends ListFragment {
private PatientAdapter pAdapter;
#Override
public void onActivityCreated(Bundle savedState) {
super.onActivityCreated(savedState);
pAdapter = new PatientAdapter(getActivity(), GFRApplication.dPatients);
setListAdapter(pAdapter);
}
}
The error:
java.lang.UnsupportedOperationException: addView(View) is not supported in AdapterView

findFragmentById(...) function takes ID of fragment(!) as parameter. But you call it with R.id.list which is ID of ListView (<ListView android:id="#+id/list" ...). It's wrong because ListView is NOT a fragment. It's the first problem.
The second problem is:
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.list, new BasicFragment());
in ft.add() function first parameter is ID of container in which you want to put your fragment. But you use R.id.list which is id of your ListView. It is wrong because ListView is not a container in which you can put fragments directly.
If you want put fragments into ListView items you can:
fill ListView with custom views.
declare <fragment ...> into custom view layout (XML). Or create fragment container in custom view layout (FrameLayout for example) and put there fragment at runtime (in getView() method).

Related

How to show fragment only when button pressed?

I'm trying to show an image below a button only after the button has been pressed. My problem is that the fragment is shown immediately when the app is started and not only after the button has been pressed.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void say_hello(View view){
Fragment fragment = new ExampleFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment2, fragment).commit();
}
}
public class ExampleFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.news_articles, container, false);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:orientation="vertical"
android:layout_height="fill_parent"
tools:context=".MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|center_vertical"
android:text="PRESS THIS"
android:id = "#+id/test_button"
android:background="#drawable/test_button"
android:onClick="say_hello"
/>
<fragment
android:id="#+id/fragment2"
android:name="com.example.tic_tac_toe.ExampleFragment"
android:layout_width="match_parent"
android:layout_height="643dp" />
</LinearLayout>
<ImageView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/cool_dog">
</ImageView>
I'm guessing the fragment shows up when the app is started because of the name I give to the fragment in the XML, but the fragment needs a name otherwise I only get error. How do I get the fragment to display nothing before I have clicked the button?
Instead of using <fragment /> view in your xml, you can use Framelayout and add your fragment to this Framelayout on button click using the following code -
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.add(R.id.mainframe, fragment);
transaction.commit();
Where mainframe is the id of Framelayout.
You can try doing this
android.app.Fragment fragment = getActivity().getFragmentManager().findFragmentByTag("YOUR_FRAGMENT_TAG");
getActivity().getFragmentManager().beginTransaction().hide(fragment);
inside your click event.

Replace one fragment with an another fragment

I want to replace an old Fragment with a new Fragment, but i still get the buttons of the old Fragment that is still visible in the new fragment.
In the old one, on a button click
FragmentTransaction transaction = getFragmentManager().beginTransaction();
Fragment newFragment = GenericMood.newInstance("a","b");
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack if needed
transaction.replace(R.id.allmoods, newFragment);
transaction.addToBackStack(null);
transaction.commitAllowingStateLoss();
I can replace the old Fragment with the new one, but the buttons from R.id.allmoods Fragment still visible on top of the new Fragment.
I tried with this given below code.
FragmentTransaction transaction = getFragmentManager().beginTransaction();
Fragment newFragment = GenericMood.newInstance("a","b");
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack if needed
transaction.replace(((ViewGroup)getView().getParent()).getId(), newFragment);
transaction.addToBackStack(null);
transaction.commitAllowingStateLoss();
XML files:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/allmoods"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorPrimary"
tools:context="com.moodoff.Moods">
<Button
android:text="Button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="64dp"
android:id="#+id/btn_btn"
android:height="80dp"
android:width="100dp"
android:onClick="putmeoff"
android:layout_marginLeft="17dp"
android:layout_marginStart="17dp"/>
</RelativeLayout>
This is the fragment that is supposed to replace the above:
<FrameLayout 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:id="#+id/genericmood"
android:layout_height="match_parent"
android:background="#color/colorPrimary"
tools:context="com.moodoff.GenericMood">
<!-- TODO: Update blank fragment layout -->
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#000000"
android:layout_gravity="fill_horizontal"
android:id="#+id/floatingButtons"
>
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="1dp"
android:layout_marginRight="14dp"
app:backgroundTint="#ffffff"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:src="#drawable/cameraicon"
android:id="#+id/btn_camera"
app:fabSize="mini"
/>
</RelativeLayout>
</FrameLayout>
Both doesn't work. What to do?
UPDATE: After replacing with the proper container the buttons had gone but the new fragment is not getting instantiated properly. I gets a pure blank white screen.
my activity_alltabs.xml looks like this:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.moodoff.AllTabs">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/background_dark" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
I Have worked on fragments before and hope this would help you out and give you a better understanding of the flow. Firstly, your MainActivity.xml file will look like this :
<?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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.activity.HomeActivity">
//This frameLayout will contain all your fragments view.
<FrameLayout
android:id="#+id/container_view"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</RelativeLayout>
Next, you create two fragments and their XML is mentioned below :
fragment1.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"
android:clickable="true" // important to have this
tools:context=".fragments.frament1">
<Button
android:id="#+id/btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"/>
</RelativeLayout>
The next fragment would look exactly the same as mentioned above. Here is the Fragment1.class:
public class Fragment1 extends Fragment implements View.OnClickListener {
Button btn;
public Fragment1() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment1, container, false);
view.setBackgroundColor(Color.WHITE);
//Perform required conditions and return view
button = (Button) view.findViewById(R.id.btn);
button.setOnClickListener(this);
return view;
}
public void onClick(View v) {
switch(v.getId())
{
case R.id.btn:
//replace current fragment on button click
Fragment fragment2= new Fragment2();
getFragmentManager().beginTransaction().
replace(R.id.container_view, fragment2).
addToBackStack("frags").commit();
break;
}
}
}
And the Fragment2 would be as follows :
public class Fragment2 extends Fragment{
String TAG = "Fragment2";
public Fragment2() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment2,container,false);
view.setBackgroundColor(Color.WHITE);
return view;
}
}
As I mentioned earlier, the xml file would be the same as fragment1.xml. What is more important here is that the main activity will contain a layout which will take the fragments view when ever the user switches fragments. Hence we use the replace method which would just replace the previous view with the fragments view specified by us.
To understand the flow of fragment transition, first of all, you have to know about its structure in activity.
Let's see:
a) Activity: At bottom of everything (MainActivity)
activity_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/container"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
Here #+id/container is the layout over we do transitions of fragment contents.
B) FragmentA : Initially added fragment to the container of MainActivity.
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
//Instance of fragment
Fragment newFragment = FragmentA.newInstance("a","b");
//It will replace the fragment content view to container of main activity
ft.replace(R.id.container, newFragment);
//FragmentA is added to back stack with it's name as a tag
ft.addToBackStack(FragmentA.class.getSimpleName());
ft.commitAllowingStateLoss();
B) FragmentB : Replace FragmentA with FragmentB
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
//Instance of fragment
Fragment newFragment = FragmentB.newInstance("a","b");
//It will replace the fragment content view to container of fragment A which // is previously replaced to main activity container
ft.replace(R.id.container, newFragment);
//FragmentB is added to back stack with it's name as a tag
ft.addToBackStack(FragmentB.class.getSimpleName());
ft.commitAllowingStateLoss();
So main thing behind this is to replace/add fragment content view to the activity container view.
In your Activity's onCreate function, you should be calling setContentView(R.layout.main), then when you want to load a Fragment, you choose a ViewParent within R.layout.main. The fragment will become the child of that ViewParent. So the id passed into FragmentTransaction.replace, is the id of the ViewParent in R.layout.main.
It makes sense that the Button in your allmoods RelativeLayout would remain because the FragmentTransaction.replace function only replaces an existing fragment that is in that container. Everything in R.layout.main will remain. This is how an Activity keeps static content, like drawers or toolbars.
When you load your "new fragment" you will use the same id. So the "new fragment" replaces the "old fragment" as the new child of the ViewParent within R.layout.main.
Here is the Fragments API guide.
Update:
When you call FragmentTransaction.replace in your Activity's onCreate function, this could be recreating an existing Fragment. Make sure the savedInstanceState (the Bundle passed into onCreate) is null. If the savedInstanceState is not null, then the fragment probably already exists and you can find it like this;
Fragment f = getFragmentManager().findFragmentByTag(YOUR_FRAGMENT_TAG);
Update 2:
Here is a guide that should help you. It looks like you could use FragmentPagerAdapter to simplify your fragment transactions.
try this once,
1. if you are passing any value upon button click
In Activity
Category category=new Category();
Bundle bundle=new Bundle();
bundle.putString("heading",heading);
bundle.putInt("position",position1+1);
bundle.putString("url",url);
bundle.putString("sku",sku);
bundle.putBoolean("flag",flag);
category.setArguments(bundle);
FragmentManager fragmentManager = getSupportFragmentManager();
final FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragmentCategories,category);
fragmentTransaction.commit();
In fragment
Bundle bundle=getArguments();
if(getArguments()!=null) {
position = bundle.getInt("position");
heading = bundle.getString("heading");
url = bundle.getString("url");
sku=bundle.getString("sku");
flag=bundle.getBoolean("flag");
tvHeading.setText(heading);
video_chapter = handler.getContent_Aspects(position);
adapter = new Chapter_content_Adapter(getActivity(), video_chapter, url, heading, position);
gvChapter.setAdapter(adapter);
}
2.if simply calling fragment
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentCategories=fragmentManager.findFragmentById(R.id.fragmentCategories);
fragmentTransaction.commit();
Try the following code.
A) Create Activity as follows :
MainActivity
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity implements ShowNextFragment{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentA fragmentA=new FragmentA();
FragmentTransaction fragmentTransaction=getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.container,fragmentA);
fragmentTransaction.addToBackStack("A");
fragmentTransaction.commitAllowingStateLoss();
}
#Override
public void showFragment() {
FragmentB fragmentB=new FragmentB();
FragmentTransaction fragmentTransaction=getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.container,fragmentB);
fragmentTransaction.addToBackStack("B");
fragmentTransaction.commitAllowingStateLoss();
}
}
B) Create 2 fragments as follows :
Fragment A
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentA extends Fragment {
private ShowNextFragment showNextFragment;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
try {
showNextFragment=(ShowNextFragment)getActivity();
Log.e("CAllback","Set");
}catch (ClassCastException e){
Log.e("Error","Please Implement ShowFragment Interface");
}
return inflater.inflate(R.layout.fragment_a,container,false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (showNextFragment!=null){
showNextFragment.showFragment();
}
}
});
}
}
Fragment B
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentB extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_b,container,false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
}
C) Create an interface as follows
public interface ShowNextFragment {
void showFragment();
}
D) create following xmls as :
i) activity_main
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
</RelativeLayout>
ii) fragment_a
<?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:background="#color/colorcyan"
android:orientation="vertical">
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Fragment B" />
</LinearLayout>
iii) fragment_b
<?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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorgreen"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fragment B"
android:layout_centerVertical="true"
android:layout_alignRight="#+id/btn_camera"
android:layout_alignEnd="#+id/btn_camera" />
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:backgroundTint="#ffffff"
android:src="#android:drawable/ic_dialog_email"
android:id="#+id/btn_camera"
app:fabSize="mini"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
The problem was the the container ID that was passing to the replace method was the ID of the fragment that was replacing, not the ID of the fragment container. This seems to explain why some of the original fragment controls were remaining after the replace - that entire fragment wasn't being replaced.
Please change it to get the fragment container view ID, and it will work! Here's the code:
transaction.replace(((ViewGroup)(getView().getParent())).getId(), fragment);
I found the answer for getting the container view ID of a fragment here, Get fragment's container view id.
Just make buttons setVisibility(View.GONE) in your activity when that fragment is begin transaction.
put your next fragment UI elements in Card View. define a LinearLayout or other view groups as root and inside this root create a Card view and put your other elements in Card View . when you inflate it in Card View then the hole of new fragment inflate on the previous fragment.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parenter code hereent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="-20dp"
app:cardCornerRadius="20dp">
......... your UI Elements .......
//, for example, define other LinearLayout inside the Card View
and put other elements inside it like TextView, Button and
so on...
</androidx.cardview.widget.CardView>
</LinearLayout>

Android fragment activity layout not finding view in multi-pane layout with findViewById

findViewById(R.id.team_detail_container) is failing to find the view. Is my problem with the xml or in the way I am constructing the FragmentActivity? How do I solve this?
To support a customised list for a fragment in the constructor of my fragment activity I have replaced
setContentView(R.layout.activity_team_list);
with
frag=(TeamListFragment)getSupportFragmentManager().findFragmentById(android.R.id.content);
if (frag==null) {
frag=new TeamListFragment();
getSupportFragmentManager().beginTransaction().add(android.R.id.content, frag).commit();
So that my class now looks like this
public class TeamListActivity extends SherlockFragmentActivity implements
TeamListFragment.Callbacks {
private boolean mTwoPane;
private TeamListFragment frag=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
frag=(TeamListFragment)getSupportFragmentManager().findFragmentById(android.R.id.content);
if (frag==null) {
frag=new TeamListFragment();
getSupportFragmentManager().beginTransaction().add(android.R.id.content, frag).commit();
}
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if (findViewById(R.id.team_detail_container) != null) {
Log.i("####", "Team Detail Container has been found! Yaay!");
mTwoPane = true;
((TeamListFragment) getSupportFragmentManager().findFragmentById(
R.id.team_list)).setActivateOnItemClick(true);
}
}
The if (findViewById(R.id.team_detail_container) != null) { condition is never met despite the fact that team_detail_container exists in the xml file that is used
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/team_list_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:orientation="horizontal"
android:showDividers="middle"
tools:context=".TeamListActivity" >
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/team_list"
android:orientation="vertical"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:paddingLeft="8dp"
android:paddingRight="8dp">
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:drawSelectorOnTop="false" />
<TextView android:id="#id/android:empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="No data"/>
</LinearLayout>
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="?android:attr/listDivider"
/>
<FrameLayout
android:id="#+id/team_detail_container"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="3" />
</LinearLayout>
I know that this particular layout xml is being used as changes I make to the xml file are reflected in the app.
I also know that the condition is never met as I never get the log message Log.i("####", "Team Detail Container has been found! Yaay!"); and the behaviour get is that when an item is selected the list view is replaced with the detail fragments instead of the detail fragments being displayed next to the list view because the item selected conditions are not being met
#Override
public void onItemSelected(int id) {
if (mTwoPane) {
// mTwoPane is never set! Why?
Bundle arguments = new Bundle();
arguments.putInt(TeamDetailFragment.ARG_ITEM_ID, id);
TeamDetailFragment fragment = new TeamDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.team_detail_container, fragment).commit();
} else {
// In single-pane mode, simply start the detail activity
// for the selected item ID.
Intent detailIntent = new Intent(this, TeamDetailSwipeActivity.class);
detailIntent.putExtra(TeamDetailFragment.ARG_ITEM_ID, id);
startActivity(detailIntent);
}
}
The fragment doesn't get added to your layout tree immediately after committing the transaction. You'll have to wait till onViewCreated on the fragment was called. You could probably access the view within the onStart-Method of your Activity, but it would probably be a better idea to keep that logic within the fragment itself. The Activity shouldn't be concerned with what views are contained in a fragment.
I think the issue is you're looking for the Fragment from the Activity, but since you're not using setContentView, the Activity doesn't actually have a View to look through. Try getting the view from the Fragment instead using the getView() method.

How to create multiple fragments programmatically?

I am trying to show multiple fragments on the one screen by creating them programmatically. I am able to do this no problem by including each fragment into the activities layout file. However when I try and do it programmatically Im confused.This is what I have so far for two fragments on a screen.
Main Class:
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentOne one = new FragmentOne();
FragmentTwo two = new FragmentTwo();
FragmentThree three = new FragmentThree();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.imOne, one, "fragmentone");
ft.add(R.id.imTwo, two, "fragmenttwo");
ft.add(R.id.imThree, three, "fragmenthree");
ft.commit();
}
}
Fragment One:
public class FragmentOne extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.frag_one, container, false);
return view;
}
}
Fragment Two:
public class FragmentTwo extends Fragment{
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.frag_two, container, false);
return view;
}
}
The layout files for my two fragment classes just contain a simple TextView.
And then the activity_main.xml layout file for my main class:
<?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="horizontal" >
<FrameLayout
android:id="#+id/imOne"
android:name="com.david.twofragexample.FragmentOne"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2" />
<FrameLayout
android:id="#+id/imTwo"
android:name="com.david.twofragexample.FragmentTwo"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2" />
<FrameLayout
android:id="#+id/imThree"
android:name="com.david.twofragexample.FragmentThree"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2" />
</LinearLayout>
When I try and do it programatically I get confused as to what should be in my activity_main.xml file. So from the Android Developer Guide(http://developer.android.com/guide/components/fragments.html) it says to use
FragmentManager fragmentManager = getFragmentManager()
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
FragmentOne fragment = new FragmentOne();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();
So when I add this code to my onCreate method what changes do I have to make to my activity_main.xml file to do this programmatically?I don't see where R.id.fragment_container comes from. How can I determine where on the screen my new fragment will go?Thanks
EDIT: I am developing this on a tablet and not a phone.This has now been solved and the above code will add three fragments programmatically.
<?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="horizontal" >
<FrameLayout
android:id="#+id/list"
android:name="com.david.twofragexample.FragmentOne"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2" />
<FrameLayout
android:id="#+id/viewer"
android:name="com.david.twofragexample.FragmentTwo"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2" />
</LinearLayout>
In your Activity:
FragmentOne one = new FragmentOne();
FragmentTwo two = new FragmentTwo();
fm = getSupportFragmentManager();
fm.beginTransaction().replace(R.id.list, one, "fragmentone").commit();
fm.beginTransaction().replace(R.id.viewer, two, "fragmenttwo").commit();
I suggest you study this:
http://developer.android.com/reference/android/app/Fragment.html
and fully understand the fragment lifecycle, etc. The way I show is quick and dirty, but not neccesarilly best.
As I don't have higher enough reps to comment yet, I will just leave the information here -- the way Rafael T suggested does work nicely, although I also had my doubt at the first place.
1) Define your xml like this:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
2) Add each fragment into the same slot:
View box = v.findViewById(R.id.container);
FragmentTransaction ft = getFragmentManager().beginTransaction();
for (String catalog : mCatalogs) {
Fragment fragment = HighlightedProductFragment.newInstance(catalog);
ft.add(R.id.container, fragment, catalog);
}
ft.commit();
Thanks for the solution for this tricky requirement.
Try it like this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
as your activity_main.xml
You asked yourself the right question: where is the id fragment_container, and the answer was: nowhere. >ou also set your layout to horizontal, which makes it very likely, that added Views will be kind of 'out of screen'

Dynamically add fragment into fragment

I haven't been able to find a way how to dynamically add fragment into existing dynamically added fragment. Do you know, if it is possible?
I am generating fragments this way:
FragmentManager fragMgr = getSupportFragmentManager();
FragmentTransaction xact = fragMgr.beginTransaction();
if(null == fragMgr.findFragmentByTag(FRAG1_TAG)) {
xact.add(10101010, new DateTime(), FRAG1_TAG);
}
if(null == fragMgr.findFragmentByTag(FRAG4_TAG)) {
xact.add(7777, new loginForm(), FRAG4_TAG);
}
xact.commit();
How to add into FRAG4_TAG fragment another one?
Edit2:
I hard coded it's id to be able to work with it in future (where ll is my linearLayout in XML):
FrameLayout frml4 = (FrameLayout)inflater.inflate(R.layout.frame,null);
frml4.setId(7777);
frml4.setBackgroundColor(Color.YELLOW);
ll.addView(frml4);
I assume the problem that you are running into is that there is not an inflated view to add the fragment to because the original fragment, FRAG4_TAG, has not been inflated before you are trying to add it.
You can pass enough information to FRAG4_TAG in the Arguments to let it know that it should create and add a fragment (or what all fragments you need it to have) to itself during it's onCreateView, after the view has been inflated...
The layout for the activity...
<?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">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="MyActivity"/>
<LinearLayout
android:orientation="vertical"
android:id="#+id/main_frag_container"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</LinearLayout>
The Activity...
public class MyActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
Fragment fragOne = new MyFragment();
Bundle arguments = new Bundle();
arguments.putBoolean("shouldYouCreateAChildFragment", true);
fragOne.setArguments(arguments);
ft.add(R.id.main_frag_container, fragOne);
ft.commit();
}
}
The layout for the fragment...
<?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"
android:padding="20dp">
<TextView
android:id="#+id/text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Some fragment"/>
<LinearLayout
android:orientation="vertical"
android:id="#+id/frag_container"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</LinearLayout>
The fragment...
public class MyFragment extends Fragment {
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
ViewGroup layout = (ViewGroup) inflater.inflate(R.layout.frag_layout, container, false);
boolean shouldCreateChild = getArguments().getBoolean("shouldYouCreateAChildFragment");
if (shouldCreateChild) {
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
fm.beginTransaction();
Fragment fragTwo = new MyFragment();
Bundle arguments = new Bundle();
arguments.putBoolean("shouldYouCreateAChildFragment", false);
fragTwo.setArguments(arguments);
ft.add(R.id.frag_container, fragTwo);
ft.commit();
}
return layout;
}
}
This example covers the case where you need to dynamically add fragments to a fragment that HAS NOT already been inflated and added to the hierarchy. Adding a fragment to a fragment that HAS already been inflated and added to the hierarchy is as simple as just specifying the target fragments container that you want to add to by ID like you would normally.
As the documentation states "A fragment must always be embedded in an activity".
So when you add a "sub-fragment" it will always belong to the activity even if you add it within your fragment class. For example if you later decide to remove the containing fragment the sub fragments won't be automatically removed.
When I had to do the same I had to store in a vector the sub fragments and manually remove them in the onDestroy methods of my container fragment.
I think that fragments are not thought to be used like this
You cannot insert Fragments into other Fragments. (At least, not yet)
You can however replace Fragments with other Fragments with FragmentTransaction.replace(containerViewId, Fragment).
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.linear1, new activity()).commit();
}

Categories

Resources