Android: Fragment layout issue - android

For large screens I have two fragments, they shall be either top/bottom or left/right. The problem is that one fragment is taking (almost) all space is taking up by one fragment. For my activity I have two main.xml (one for portrait one for landscape). But they are basically similar (apart from orientation).
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" android:id="#+id/frag_cont" >
</LinearLayout>
In onCreate I add my fragments to that layout:
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
OverviewFragment of = new OverviewFragment();
FragmentTransaction tof = getFragmentManager().beginTransaction();
tof.add(R.id.frag_cont, of);
DetailFragmentInitial df = new DetailFragmentInitial();
tof.add(R.id.frag_cont, df);
tof.commit();
}
The two fragments look kind of similar in terms of onCreateView()
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.inflate(R.layout.overview, container, false);
}
Finally the two xml files for these fragments look like this, first the smaller fragment:
<?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" android:layout_weight="1">
<ImageView
android:id="#+id/imageLogo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/logo"
android:layout_centerInParent="true" />
<TextView
android:id="#+id/textB"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="text"
android:layout_above="#id/imageLogo"
android:layout_centerHorizontal="true"/>
</RelativeLayout>
And now the greedy one taking the space:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:layout_weight="10000" >
<ListView
android:id="#+id/ListView01"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
I assumed that when I set both layout_weight to 1 then both will take the same amount of space, but even with the setting 1000:1 the bigger one takes about 2/3 of the space. Leaving the weight away will give the bigger fragment all the screen and the other one is not visiable at all. Any ideas?
Edit:
I followed the approach given below. Much better now in terms of space. On screen rotate the overview fragment (basically list view) is empty, the other fragment is still okay.
In OverviewFragment.java I repopulate the fragment in onActivityCreated():
public void onSaveInstanceState(Bundle bundle)
{
bundle.putSerializable("list", mList);
super.onSaveInstanceState(bundle);
}
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
if(savedInstanceState != null)
{
mList = (ArrayList<myObject>) savedInstanceState.getSerializable("list");
}
else
{
mAppList = new ArrayList<myObject>();
new getApps().execute();
}
ListView lv = (ListView) getActivity().findViewById(R.id.ListView01);
lv.setOnItemClickListener(new TableItemSelected());
mItemAdapter = new ItemAdapterOverview(getActivity().getApplicationContext(), mList);
lv.setAdapter(mItemAdapter);
}
when rotating the screen the onSaveInstanceState() is called first and then onActivityCreated() twice. The first call the saveInstanceState is not null, the second time it is. Anyway in both cases I should see my list, either build up from scratch or the saved list. Why isn't it and why is that method called twice?

Not entirely sure whether this will be causing your issue (I suspect it does), but using FragmentTransaction.add(..) doesn't add the Fragment into the container, it essentially replaces the container with that Fragment. The issue here is that you're adding both Fragments to the same container so they will take up the same space and cause issues.
A better way to do this would be to add two container views into your frag_cont LinearLayout (e.g. FrameLayouts), and give them two separate ids (e.g. frag_one and frag_two). Then in your onCreate(..), change it to read:
FragmentTransaction tof = getFragmentManager().beginTransaction();
tof.add(R.id.frag_one, of);
DetailFragmentInitial df = new DetailFragmentInitial();
tof.add(R.id.frag_two, df);
tof.commit();
This will make it so that the layout with id frag_one is filled by the OverviewFragment and the one with id frag_two replaced by the DetailFragmentInitial. You can then use the views in main.xml to tweak the sizes of the fragments as you see fit.

Related

Fragment Question, where to build buttons etc

I am using fragments to update a text view I have so when the person clicks a button the text view moves on to the next question. I'm not sure if I am doing the correct work in one fragment instead of the other. My current screen looks like this:
I will probably have to add some more buttons/widgets to this but should I be adding it into the XML for the fragment or the fragment container?
Here is XML for fragment actions:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/fragment_question_layout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context=".FragmentActions"
>
<!-- this is where fragments will be shown-->
<FrameLayout
android:id="#+id/question_container1"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="4"
android:scaleType="centerInside" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/questions_yes1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="#string/yes" />
<Button
android:id="#+id/questions_no1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="#string/no" />
</LinearLayout>
</LinearLayout>
And here is the fragment details:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/button_layout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
tools:context=".FragmentDetails">
<!--Blank Fragment Layout-->
<TextView
android:id="#+id/questions_text_view1"
android:layout_width="match_parent"
android:layout_height="91dp"
android:gravity="center"
android:textAlignment="center"
/>
</FrameLayout>
Updated FragmentDetails
public class FragmentDetails extends Fragment {
private final String TAG = getClass().getSimpleName();
private List<Integer> mQuestionIds;
private int mListIndex;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//Inflate the fragment layout
View rootView = inflater.inflate(R.layout.fragment_details, container, false);
//Get a reference to the textView in the fragment layout
final TextView textView = (TextView) rootView.findViewById(R.id.questions_text_view1);
if (mQuestionIds != null) {
textView.setText(mQuestionIds.get(mListIndex));
//Increment the position in the question lisy as long as index is less than list length
if (mListIndex < mQuestionIds.size() - 1) {
mListIndex++;
setmQuestionIds(QuestionList.getQuestions());
setmListIndex(mListIndex);
} else {
//end of questions reached
textView.setText("End of questions");
}
//Set the text resource to display the list item at that stored index
textView.setText(mQuestionIds.get(mListIndex));
}
else {
//Log message that list is null
Log.d(TAG, "No questions left");
}
//return root view
return rootView;
}
public void setmQuestionIds (List < Integer > mQuestionIds) {
this.mQuestionIds = mQuestionIds;
}
public void setmListIndex ( int mListIndex){
this.mListIndex = mListIndex;
}
}
Fragment Actions activity
public class FragmentActions extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_actions);
Button yes = findViewById(questions_yes1);
// Only create new fragments when there is no previously saved state
if (savedInstanceState == null) {
//Create Question Fragment
final FragmentDetails fragmentDetails = new FragmentDetails();
fragmentDetails.setmQuestionIds(QuestionList.getQuestions());
yes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//set the list of question Ids for the head fragent and set the position to the second question
//Fragment manager and transaction to add this fragment
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.question_container1, fragmentDetails)
.commit();
}
});
}
}
}
If your Buttons remain the same while the TextView changes, you may add your Buttons to the fragment container.
Remember that, your fragments will be presented inside the FrameLayout of the fragment container. You gotta keep your Buttons, outside the FrameLayout.
Or if you want to have different Buttons for different fragments (Questions, in your case), you can also add the Buttons to the fragments. But in that case, you gotta add them separately to each of the fragments.
I guess there's no right answer to your question. You could try different approaches.
Maybe you could implement the buttons in the fragment container, as #smmehrab pointed out. I see this as a more difficult solution, because when you click on an item from the container you can manage the views of the container, not the fragment's views. You would get NullPointer if I recall correctly. This happens because the context when the button is clicked in the fragment container is different than the context when clicking from within the fragment. So you should implement an interface on the fragment container that listens to clicks, and the fragment catches the click. You could do this, and I actually am doing it in my current app, but I have no choice.
You could instead use Motion Layout (which extends from Constraint Layout) as the root view of your fragment, instead of CardView. This way you could set all the fragment's views with a flat hierarchy (flat hierarchies improves rendering time, so that's an improvement, and you can use CardView as one child) and set the buttons right there, in the Motion Layout (remember, the motion layout would be the fragment's root view). You could set the click listener right there and implement animations between different textViews.
I'm sure there are plenty of other solutions, take this only as a contribution.
If you're unfamiliar with Motion Layout you can just google it, android official documentation about it is great.

How to replace an Android fragment with another fragment inside a ViewPager?

I have a view pager consisting of 4 tabs. Each tab holds its own fragment.
How would I be able to use fragment transaction to replace the fragment in tab 3 with a new fragment?
I've tried a lot of things, but I have not been able to come up with a solution at all. I've tried looking around on google and stackoverflow, but with no success.
I assume that your fragment has a button that is put in the center. By clicking on it, you can change the layout stays under of this button. The content/layout of the first fragment you mentioned should be replaced with wrapperA and the content/layout of the second one should be replaced with wrapperB. I put a simple red background for wrapperA to distinguish it with wrapperB, wrapperB is also green due to the same reason. I hope this is what you want:
public class SwitchingFragment extends Fragment {
Button switchFragsButton;
RelativeLayout wrapperA, wrapperB;
View rootView;
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.layout_switch, container, false);
wrapperA = (RelativeLayout) rootView.findViewById(R.id.wrapperA);
wrapperB = (RelativeLayout) rootView.findViewById(R.id.wrapperB);
switchFragsButton = (Button) rootView.findViewById(R.id.switchFragsButton);
switchFragsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (wrapperB.getVisibility() == View.GONE) {
wrapperB.setVisibility(View.VISIBLE);
// There is no need to change visibility of wrapperA since it stays behind when wrapperB is visible.
// wrapperA.setVisibility(View.GONE);
}
else {
wrapperB.setVisibility(View.GONE);
// Again, there is no need.
// wrapperA.setVisibility(View.VISIBLE);
}
}
});
return rootView;
}
}
The layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:orientation="vertical">
<!-- The content of first fragment should be in "wrapperA". -->
<RelativeLayout
android:id="#+id/wrapperA"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/red"
android:visibility="visible">
</RelativeLayout>
<!-- The content of second fragment should be in "wrapperB". -->
<RelativeLayout
android:id="#+id/wrapperB"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/green"
android:visibility="gone">
</RelativeLayout>
<!-- As I said, I assume that the layout switcher button is stable
and so it should be in front of the switching layouts. -->
<Button
android:id="#+id/switchFragsButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:background="#color/black"
android:text="Switch"
android:textSize="20sp"
android:textStyle="bold"
android:textColor="#color/white"/>
</RelativeLayout>
Alternatively, you can try to change the fragment directly by notifying your FragmentPagerAdapter as described in this link:
Replace fragment with another fragment inside ViewPager

Android Fragment only uses last value for edittext after second "refresh"

I've got a fragment which dynamially adds LinearLayouts with two imagebuttons and a edittext.
The Value from the edittext is stored in a .txt File and retrieved via the function retrievecounter.
This is the Layout which gets added:
<?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="wrap_content"
android:orientation="horizontal"
android:weightSum="100" >
<ImageButton
android:id="#+id/imageView1"
android:layout_width="56dp"
android:layout_height="50dp"
android:layout_weight="5"
android:src="#drawable/ic_action_photo" />
<EditText
android:id="#+id/singelfirstet1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="85"
android:ems="10" >
<requestFocus />
</EditText>
<ImageButton
android:id="#+id/buttonDelete"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="10"
android:background="#android:color/transparent"
android:contentDescription="#string/button_delete_row_description"
android:src="#drawable/testi" />
</LinearLayout>
This is my fragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
ScrollView mLinearLayout = (ScrollView) inflater.inflate(
R.layout.editlistsfirst, container, false);
operations = new ArrayList<String>();
operations = retrievecounter(0);
temp = (LinearLayout) mLinearLayout.findViewById(R.id.lineartest);
LayoutInflater inflater2 = (LayoutInflater) getActivity()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
for (int i = 0; i < operations.size(); i++) {
View tempr = (inflater2.inflate(R.layout.list_singlefirst,
container, false));
ImageButton bt = (ImageButton) tempr
.findViewById(R.id.buttonDelete);
EditText et = (EditText) tempr.findViewById(R.id.singelfirstet1);
et.setText(operations.get(i));
String show = et.getText().toString();
Log.w("Class",show);
bt.setOnClickListener(this);
temp.addView(tempr);
}
return mLinearLayout;
}
I navigate between the fragments via an actionbar with tabs.
This is my onTabselected function:
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
ft.replace(R.id.fragment_container, fragment);
}
On the first click the values from the .txt file are displayed correctly, but after i switch to a different tab/fragment and back to this fragment only the last value of my ArrayList gets displayed.
Strange however is that the Log.w displays the correct value for the edittext both times.
Any idea what causes this?
Thanks in advance
If i call my function of the button inside the linearlayout:
temp.removeView((View) v.getParent());
for all buttons till all layouts are gone and go to another tab and back it displays the correct values, but i've got no idea why. Maybe this is helpful in finding the problem.
edit2: I Found a solution, don't know if it is practical or why it works but it does:
public void onPause(){
super.onPause();
temp.removeAllViews();
}
After i added this it works. If someone could explain why that would be much appreciated.
One of the things to consider when dealing with Views like this is that they are only 'updated' when they are first created. When you switch between your tabs, the data will not be refreshed because it was A)Not recreated [refreshed] B)Not updated by an adapter.
When you removed all views on Pause(), you emptied your view, then it is recreated from your replace() function which is similar as creating a new view. Refreshing a layout by removing and re-adding everything every time you change something can become very computationally expensive which is why people will use an adapter to control their layouts.

Android Fragment : bug fix explanation

I'm starting using Fragments, and I've done like the API guide but ... of course it'd be too easy ;)
When I launch the app, it crashes. After some research I've found this post Android fragment is not working
and the response of Stephen Wylie seems to correct the things for Ali, but .. I don't get it !
Where should I put the FrameLayout ? The "where_i_want_my_fragment" id... it's whatever I want, right ?
and finally where should I put the Java code ? in my activity (which is displaying 2 fragments by the way) .
Thanks !
Nico
EDIT : Let's just say what I want for design you would understand better I think.
I want a list fragment on left side which display a list of strings, and to the right side I want a fragment displaying info regarding the selected string in the list. And I wanna be able to swip with fingers movements the right side of my app (I dont know if it s better to swipe fragment or whatever.. It's the same layout but filled with differents datas)
Ok I just post my code because I really don't see why it doesn't do anything.
This is my activity_main.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:baselineAligned="false"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/list_frag"
android:name="main.courante.c.DateListFragment"
android:layout_width="fill_parent"
android:layout_height="match_parent" >
</FrameLayout>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fiche_frag"
android:name="main.courante.c.fiche_frag"
android:layout_weight="2"
android:layout_width="0dp"
android:layout_height="match_parent" >
</FrameLayout>
</LinearLayout>
Here is my main activity :
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DateListFragment fragment = new DateListFragment();
getFragmentManager().beginTransaction().add(R.id.list_frag, fragment).commit();
fiche_freg frag2 = new fiche_frag();
getFragmentManager().beginTransaction().add(R.id.fiche_frag,frag2).commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
Here is DateListFragment (no onCreateView because it 's automatically generated)
public class DateListFragment extends ListFragment {
private int mposition = 1;
private String[] mListItem = new String[] {
"Lundi 9 Juilllet",
"Mardi 10 Juillet",
"Mercredi maintenant"
};
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
this.setListAdapter(new ArrayAdapter<String>
(this.getActivity(),R.layout.frag_list_view ,mListItem));
this.getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}
and here is fiche_frag :
public class fiche_frag extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.checks_matin,container,false);
}
R.layout.checks_matin works fine alone.
I thank you already and again for your help. I'm a beginner in android environnement and I find it difficult to englobe every notions for the UI at once... !!
You understand the basics. The FrameLayout goes wherever you want your fragment(s) to go. I've done it where my whole screen was one single FrameLayout before and I swapped up to five different fragments in and out of it.
If you have two Fragments that you want to display simultaneously, you could make your main layout with two FrameLayouts. However, this means you are locked into having both there all the time (or an empty space if you remove one.
If you want two fragments that don't have to be on the screen at the same time you use a single FrameLayout and write code to swap the fragments as required.
Code to instantiate fragments should always be in the controlling activity (if they are dynamic).
Without code and a more specific problem, the above is the best answer I can give you.
EDIT
An example main layout to put two fragments side by side:
<?xml version="1.0" encoding="utf-8"?>
...
<LinearLayout
android:id="#+id/frames"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#id/hline1"
android:layout_below="#id/horizontalline"
android:orientation="horizontal" >
<FrameLayout
android:id="#+id/leftpane"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight=".4" />
<FrameLayout
android:id="#+id/rightpane"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="1" >
</FrameLayout>
</LinearLayout>
...
To add your fragment to one of the framelayouts:
FragmentClass fragment = new FragmentClass();
getFragmentManager().beginTransaction().add(R.id.leftpane, fragment).commit();
If you want to swap fragments in one of the framelayouts (say the left pane), you can do it like this:
FragmentClass fragment = new FragmentClass();
getFragmentManager().beginTransaction().replace(R.id.leftpane, fragment).commit();
I suggested instantiating from the XML because it sounded like you were going to have two fragments and not make any changes. If you are going to swap them in and out, then it would be appropriate to add a tag to each one so you can find them again if you want to display them again.

Transitioning from one ListFragment to another

I'm trying to build a basic ListFragment based application which transitions from one ListFragment to another, based upon user input.
I make use of the default ListView that the Android system inflates for a ListFragment, thus I dont over-ride onCreateView().
To set the margins around the ListFragment, I add a GlobalLayoutListener.
Now, when I launch the application, the first screen containing the default fragment shows up properly, with the margins set correctly.
But as soon as I click an image in the main layout, which invokes a transition to a second fragment having the same onActivityCreated() method and the GlobalLayoutListener as the first fragment, I get the dreaded Content View not created yet error in the OnGlobalLayout() method when I try to access the ListView in the second fragment.
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(getActivity(),
R.layout.listcommon, R.id.label, MAIN_TITLES));
ListView lv = getListView();
lv.setDivider(null);
lv.setDividerHeight(0);
lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
lv.setItemChecked(0, true);
lv.setSelection(0);
ViewTreeObserver observer = getListView().getViewTreeObserver();
observer.addOnGlobalLayoutListener(fragmentLayoutListener);
}
ViewTreeObserver.OnGlobalLayoutListener fragmentLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener(){
public void onGlobalLayout() {
//Crashes here for second fragment
ListView listView = getListView();
FrameLayout.LayoutParams params = (LayoutParams) listView.getLayoutParams();
params.setMargins(10, 10, 10, 10);
}
};
Here's the main layout: (Default fragment gets added through FragmentTransaction.add() to first FrameLayout)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:baselineAligned="false"
android:background="#00000000">
<FrameLayout
android:id="#+id/TitlesContainer"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="40"
android:layout_margin="10dip"
android:background="#drawable/titlesbg"
>
</FrameLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="60"
android:background="#00000000"
>
<ImageView
android:id="#+id/imageView_clickWheel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:src="#drawable/clickImage" />
</FrameLayout>
</LinearLayout>
Any thoughts on what I should be doing to avoid running into this error?
Should I be over-riding onCreateView() after all and inflate a custom list view (but I have no such need)?
EDIT:
Here's how I add the default fragment to the main activity's onCreate():
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
TitlesFragment fragment = (TitlesFragment) fragmentManager.findFragmentByTag(MAIN_SCREEN_TAG);
if (fragment == null){
fragment = TitlesFragment.newInstance(SCREEN_MAIN);
fragmentTransaction.add(R.id.TitlesContainer, fragment, MAIN_SCREEN_TAG);
} else {
fragmentTransaction.add(R.id.TitlesContainer, fragment);
}
fragmentTransaction.commit();
To perform the transition, this is what I do:
fragment = (TitlesFragment) fragmentManager.findFragmentByTag(SECOND_FRAGMENT_TAG);
if (fragment == null){
fragment = TitlesFragment.newInstance(SECOND_FRAGMENT);
fragmentTransaction.replace(R.id.TitlesContainer, fragment, SECOND_FRAGMENT_TAG);
} else {
fragmentTransaction.replace(R.id.TitlesContainer, fragment);
}
fragmentTransaction.commit();
Since you didn't mention it and haven't shown your full code, I'm guessing a bit here, but the following could be the cause of your issue.
I think you need to create your view first before you can access elements of it. See here and here.
An example from one of my projects:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.leftlistfragment, container, false);
return v;
}
EDIT
Maybe the issue is the way you are creating the fragment (I'm not familiar with the method you are using with tags). Maybe this might work for you too:
titleFrag = new TitlesFragment();
getFragmentManager().beginTransaction()
.replace(R.id.TitlesContainer, titleFrag, SECOND_FRAGMENT_TAG).commit();
I got rid of the OnGlobalLayoutListener. Instead I set 'layout_padding' attribute on the first FrameLayout to set the margins on the Fragment that it encloses.

Categories

Resources