My layout was working fine before I switched it to use fragments inside the DrawerLayout. After that the ListView in the main view ghosts a copy of the list when scrolling.
The ListView contents scroll, but a copy of the first page remains on screen. I've been logging debug messages and there is no second copy of listview created, and no second copy of data sent from the adapter.
The layout for the activity uses DrawerLayout with fragments before switching to fragments it worked fine.
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="400dp"
android:layout_height="800dp">
<!-- The main content view -->
<fragment android:name="com.nosweatbudgets.receipts.ReceiptsFragment"
android:id="#+id/receipts_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<!-- The navigation drawer -->
<fragment android:name="com.nosweatbudgets.navigate.NavigateFragment"
android:id="#+id/navigate_fragment"
android:layout_width="300dp"
android:layout_height="match_parent"
android:layout_gravity="start"
/>
</android.support.v4.widget.DrawerLayout>
The fragment classes are each very simple.
ReceiptsFragment's onCreateView looks like this.
View view = inflater.inflate(R.layout.receipts, container, false);
_adapter = new ReceiptsAdapter(inflater);
ListView list = (ListView) view.findViewById(R.id.receipt_list);
list.setAdapter(_adapter);
_adapter.Refresh();
return view;
NavigateFragment's onCreateView is basically the same with a different adapter. It's the ReceiptsFragment that is ghosting while the NavigateFragment does not ghost. Yet they can basically the same approach.
View view = inflater.inflate(R.layout.navigate, container, false);
_navigate = new NavigateAdapter(inflater);
// setup the list view for the side
ListView list = (ListView) view.findViewById(R.id.left_drawer);
list.setAdapter(_navigate);
_navigate.Refresh();
return view;
For the above fragment classes I'm using the following layouts.
receipts.xml looks like this.
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/receipt_list"/>
</RelativeLayout>
navigate.xml looks like this.
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<ListView
android:id="#+id/left_drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:choiceMode="singleChoice"
android:background="#EEEEEE"/>
</RelativeLayout>
The pull out navigate listview works just fine, but the main receipts listview has the ghosting problem.
I'm completely stumped as to what is causing this.
EDIT:
Here is how views are created in the ReceiptsAdapter.
public View getView(int position, View convertView, ViewGroup parent)
{
View view = convertView;
if (view == null)
{
view = _inflater.inflate(R.layout.receipt, null);
}
TextView txt_vendor = (TextView) view.findViewById(R.id.receipt_vendor);
TextView txt_category = (TextView) view.findViewById(R.id.receipt_category);
TextView category_btn = (TextView) view.findViewById(R.id.category_btn);
Model receipt = _receipts.get(position);
int vendor_id = receipt.getAsInteger("smart_vendor_id");
int category_id = receipt.getAsInteger("smart_category_id");
if (_vendors.indexOfKey(vendor_id) >= 0)
{
txt_vendor.setText(_vendors.get(vendor_id));
}
else
{
txt_vendor.setText("Select Vendor");
}
if (_categories.indexOfKey(category_id) >= 0)
{
String cat = _categories.get(category_id);
txt_category.setText(cat);
category_btn.setText(Category.ShortTitle(cat));
category_btn.setBackgroundColor(Category.Color(cat));
//txt_category.setBackgroundColor(c);
}
else
{
txt_category.setText("Select Category");
category_btn.setText("N/A");
}
((TextView) view.findViewById(R.id.receipt_amount)).setText("$" + receipt.getAsString("amount"));
((TextView) view.findViewById(R.id.receipt_payment)).setText(receipt.getAsString("payment"));
((TextView) view.findViewById(R.id.receipt_date)).setText(receipt.getAsString("receipt_date"));
return view;
}
EDIT:
This is how the Activity for the layout attaches the fragments via the onCreate method.
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// the layout uses fixed width/size, because the layout editor won't render match_parent.
// so I replace the layout parameters here with match_parent.
DrawerLayout layout = (DrawerLayout) getLayoutInflater().inflate(R.layout.main, null);
DrawerLayout.LayoutParams param = new DrawerLayout.LayoutParams(ViewGroup.LayoutParams
.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
layout.setLayoutParams(param);
setContentView(layout);
// configure this activity
StyleActionBar();
// Add the fragments
getSupportFragmentManager().beginTransaction()
.add(R.id.navigate_fragment, new NavigateFragment())
.add(R.id.receipts_fragment, new ReceiptsFragment())
.commit();
}
I mistakenly followed the fragments tutorial incorrectly, and created both a static fragment in the layout XML and also created a dynamic fragment for the same class at run-time.
The main layout used the <fragment> tag to create a fragment which is automatically attached at runtime via the android:name property.
This is what I have in my layout.xml
<fragment android:name="com.nosweatbudgets.receipts.ReceiptsFragment"
android:id="#+id/receipts_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
That was enough to create the fragment, but I mistakenly added code from the fragments tutorial in my activity as follows.
getSupportFragmentManager().beginTransaction()
.add(R.id.navigate_fragment, new NavigateFragment())
.add(R.id.receipts_fragment, new ReceiptsFragment())
.commit();
That added two additional fragment views to the activity at runtime. This resulted in two listviews for the same position.
What appeared to be a ghosting artifact was infact two fragments for the same class on top of each other. Removing the dynamic creation in onCreate resolved my problem.
Related
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.
Hi there (and thanks in advance),
I have an application with a Google Play Store-like layout (using PagerTabStrip with 5 sub fragments). In some of those fragments I will need to display a little info regarding the last time the data was updated.
I immediately thought of creating a fragment (LastUpdatedFragment) which I would then add (nest) to the fragments I needed. At first, and since the last updated date was supposed to be the same for every screen, things were working (I simply added the fragment in the xml of the parent Fragments I needed and inside onCreateView I would put the date in the TextView), but after some changes I now need to send a specific date for each one of these LastUpdatedFragment instances.
I came up with one way - creating new custom attributes for my Fragment and then I would set the date I wanted. After some reading I stumbled across a easier way (Fragments within Fragments - dinamically adding the fragment using FragmentManager) - I simply needed the parent Fragment to handle the input parameters and pass it to the child fragment.
The problem is that, although I get no errors I also get no child fragment, it just does not display. I would be grateful if you could guide me in the right direction.
ScoreBoardFragment.java -> Parent Fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_scoreboard, container,
false);
for (int i = 0; i < tvCount; i++) {
tvName = "f_scoreboard_header_tv" + String.valueOf(i);
resID = getResources().getIdentifier(tvName, "id",
_activity.getPackageName());
header = (TextView) rootView.findViewById(resID);
header.setTypeface(MyGlobalConfig.getInstance().getHeadersFont());
}
FragmentManager childFragMan = getChildFragmentManager();
FragmentTransaction childFragTrans = childFragMan.beginTransaction();
LastUpdatedFragment fragB = new LastUpdatedFragment();
childFragTrans.add(R.id.FRAGMENT_PLACEHOLDER, fragB);
childFragTrans.addToBackStack("B");
childFragTrans.commit();
return rootView;
}
fragment_scoreboard.xml (simplified but displaying everything else)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/FRAGMENT_PLACEHOLDER"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
style="#style/ListView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/f_scoreboard_header_tv0"
style="#style/ListViewRowHeader"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#" />
</LinearLayout>
<ListView
android:id="#+id/f_scoreboard_lvbody"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true" >
</ListView>
</LinearLayout>
LastUpdatedFragment.java -> Child Fragment
public class LastUpdatedFragment extends Fragment{
private View rootView;
private TextView tv;
private Context ctx;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(
getActivity()));
this.ctx = getActivity().getApplicationContext();
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_date, container,
false);
tv = (TextView) rootView.findViewById(R.id.f_date_tv);
tv.setTypeface(MyGlobalConfig.getInstance().getBodyFont());
tv.setText(getString(R.string.lastupdated) + ": " + Util.getLastUpdated(ctx));
return rootView;
}
}
fragment_date.xml
<?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" >
<TextView
android:id="#+id/f_date_tv"
style="#style/LastUpdatedTV"
android:layout_width="match_parent"
android:text="Data de última actualização: 27/12/2014 21:30" />
</LinearLayout>
Try to use FrameLayout instead of LinearLayout as Placeholder.
There's very little literature on this topic, and google's documents don't account for the possibility of customization (listviewanimation) of the fragment's list using ListFragment extension. Therefore, I'm going to ask this question, and then answer it as best as possible, because I also want 50 reputation points so I can finally thank great explainers on this website through comments.
For the purpose of this comment, I will have components from the listviewanimation lib laced in:
https://github.com/nhaarman/ListViewAnimations
Answer:
We will need to set up 4 components to have a proper fragment with a listview component
The Activity Creating the fragment through the activity's fragment manager.
The Fragment class which will be pretty basic fragment stuff, it will have the listview, and it will link that listview with an arrayadapter.
The Adapter class which for our purposes will only handle strings.
WITHIN THE ADAPTER CLASS the final fourth component will be a viewholder class which will allow the rows within the list to be created faster, since each row's individual components will be wrapped up in a class that will allow for quicker object instantiation.
Ok so, first will be the code for the activity, this code can be called by a button click or some other event. When the event happens, the fragment manager will be created, and that fragment manager will create a transaction which is a fancy way of saying, the manager will communicate between the activity and the newly formed fragment to get everything set up properly.
Here's the code that should be placed in your activity where the event occurs:
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
GenericFragment fragment = new GenericFragment();
fragmentTransaction.add(R.id.pager, fragment);
//Replace R.id.pager with the view that you want your fragment to go in.
fragmentTransaction.commit();
That's it! Not so bad, is it? Now let's move on to the GenericFragment class, which you can create a different name of course. I won't be posting all the code for this, but I'll step through everything you need for a fragment class that has a listview:
Have your Fragment class extend Fragment
Have an empty constructor for this class (google requires it... -__- )
Create a newInstance method which will handle the passing of data from the activity to the fragment when a 'new instance' of the fragment is created from the activity:
I'll help you with this one:
public static GenericFragment newInstance(String StuffYouWantGetsPassedFromActivityToFragment) {
GenericFragment GenericFragment = new GenericFragment();
Bundle args = new Bundle();
GenericFragment.setArguments(args);
return GenericFragment;
}
Again not so bad, right? We're still not done, we still need to override onCreateView and onCreate, then we'll be done with this simple step!
Ok for onCreateView:
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.generic_fragment_layout, container, false);
addGoalButton = (Button) view.findViewById(R.id.btn_newRow); //Created for testing purposes
lv = (ListView) view.findViewById(R.id.GenericListView);
addGoalButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { //Created for testing purposes
genericAdapter.add("Goal");
genericAdapter.notifyDataSetChanged();
}
});
lv.setAdapter(genericAdapter);
return view;
}
That above code may seem like a monstrosity, and you're right! The high level overview is that you're getting the layout file that you want the fragment to look like. From that layout file, you're getting the listview and creating a variable to hold it in. Then you're calling that listView's 'setAdapter' method to add the next step, the adapter class. For testing purposes, I added that button, so that you can mentally extend this tutorial l8er. (delete all button code if you'd like just a list)
Ok, one last step in the fragment class: Overriding OnCreate!
The OnCreate method is where you want to instantiate all your private variables like the genericAdapter variable or anything that you'd like to use over the multiple parts of the Fragment class.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayList<String> exampleItemList = new ArrayList<String>();
exampleItemList.add("item1");
exampleItemList.add("item2");
exampleItemList.add("item3");
exampleItemList.add("item4");
exampleItemList.add("item5");
exampleItemList.add("item6");
exampleItemList.add("item7");
exampleItemList.add("item8");
exampleItemList.add("item9");
exampleItemList.add("item10");
exampleItemList.add("item11");
exampleItemList.add("item12");
genericAdapter = new genericAdapter(getActivity(), 0, exampleItemList);
setHasOptionsMenu(true); // Allows the fragment to change the menu buttons
}
I added the example items to an arrayList to make this tutorial a bit more transparent about where data is coming from, and where it's going.
That's it! You're Fragment is done! It's almost over, I promise.
Let's knock these last two steps out together, creating a GenericAdapter class that extends ArrayAdapter and has a private inner ViewHolder class to wrap all the layout components in:
public class GenericAdapter extends ArrayAdapter<String>
LayoutInflater layoutInflater;
//Used to get the correct LayoutInflater to inflate each row item
public GenericAdapter(Context context, int resource, List<String> objects) {
super(context, 0, objects);
layoutInflater = layoutInflater.from(context);
}
/**
* #param position The position in the list to get the data for that row item.
* #param convertView The view for the row item that will be shown in the list.
* #param parent Having this object allows you to use the LayoutInflater for the parent.
* #return
*/
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final GenericViewHolder GenericViewHolder;
final String item = getItem(position);
if(convertView == null){
LinearLayout rootView = (LinearLayout) layoutInflater.inflate(R.layout.item_row, parent, false);
genericViewHolder = genericViewHolder.create(rootView);
rootView.setTag(genericViewHolder);
}
else{
genericViewHolder = (genericViewHolder) convertView.getTag();
}
genericViewHolder.textView.setText(item);
return genericViewHolder.rootView;
}
/**
* ViewHolder's allow for a single object to maintain a Goal row item, so that the row item
* doesn't have to create each individual component (textview layout etc.) each time the
* row object is created/recreated. Allows for fast scrolling with little latency.
*/
private static class GenericViewHolder {
public final LinearLayout rootView;
public final GripView gripView;
public final TextView textView;
private GoalViewHolder(LinearLayout rootView, GripView gripView, TextView textView) {
this.rootView = rootView;
this.gripView = gripView;
this.textView = textView;
}
public static GoalViewHolder create(LinearLayout rootView){
TextView textView = (TextView)rootView.findViewById(R.id.list_row_draganddrop_textview);
GripView gripView = (GripView)rootView.findViewById(R.id.list_row_draganddrop_touchview);
return new GenericViewHolder(rootView, gripView, textView);
}
}
}
That was again, a monstrosity, let's look at the high level overview, we created an adapter class, and a viewholder class for the adapter class to use. In the adapter's constructor we got a layoutinflater to help with inflating each row's item. Then, we created the getView method which get's called thousands of times in your app, because it handles making the each row appear when it's viewable by the user. The getView method sees if the view to be converted into a row is null or not. If it is, it will create a new data entry (a viewholder), but if it's not null, then that viewholder has already been created, so we get whatever was inside the viewholder already, so that we don't have to create a new row item.
phew! I don't expect you to understand any of that, but congrats if you do.
Ok so that's it. You should be set, and when your activity's event get's called, the fragment will show up in whatever view is containing the fragment. I'll post my xml files in my answer so that I can get those delicious upvotes (or not, I may be completely incorrect, but this worked for me!)
enjoy life, don't give up!
The activity xml, most of it is irrelevant to you the reader, but the container view for the fragment is pager:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<!--Navigation Drawer Still Under Construction-->
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- As the main content view, the view below consumes the entire
space available using match_parent in both dimensions. -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- android:layout_gravity="start" tells DrawerLayout to treat
this as a sliding drawer on the left side for left-to-right
languages and on the right side for right-to-left languages.
The drawer is given a fixed width in dp and extends the full height of
the container. A solid background is used for contrast
with the content view. -->
<ListView
android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#ffff"/>
</android.support.v4.widget.DrawerLayout>
<!--Navigation Drawer Still Under Construction-->
<!--Customizations on README at: https://github.com/astuetz/PagerSlidingTabStrip-->
<com.astuetz.PagerSlidingTabStrip
android:id="#+id/tabs"
android:layout_width="wrap_content"
android:layout_height="48dip"
app:pstsShouldExpand="true"
app:pstsIndicatorHeight="5dip"
app:pstsDividerPadding="0dip"
app:pstsDividerColor="#ff6d00"
app:pstsUnderlineColor="#ff5722"
app:pstsIndicatorColor="#ff5722"/>
<!--To scale the viewpager vertically, android:layout_above="#+id/[viewname]" -->
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/tabs"
tools:context=".MainActivity" />
</RelativeLayout>
The xml layout for the fragment:
<?xml version="1.0" encoding="utf-8"?>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="New Item"
android:id="#+id/btn_newItem"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<com.nhaarman.listviewanimations.itemmanipulation.DynamicListView
android:id="#+id/GenericListView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_above="#+id/btn_newGoal" />
The specific row item:
<?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:layout_width="match_parent"
android:layout_height="wrap_content"
tools:ignore="UseCompoundDrawables">
<com.nhaarman.listviewanimations.itemmanipulation.dragdrop.GripView
android:id="#+id/list_row_draganddrop_touchview"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:color="#android:color/darker_gray"
android:paddingBottom="4dp"
android:paddingLeft="8dp"
android:paddingRight="8dp"
android:paddingTop="4dp" />
<TextView
android:id="#+id/list_row_draganddrop_textview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-light"
android:gravity="center_vertical"
android:minHeight="48dp"
android:textColor="?android:attr/textColorSecondary"
android:textSize="20sp"
tools:ignore="UnusedAttribute" />
</LinearLayout>
The layout portion of the 2nd code snippet got cut off and SO wasn't agreeing with my ctrl K'ing, but the long and short of it, is that it doesn't matter, because the listview is there, so it doesn't matter whether you put it in a linear layout or a relative layout.
Good luck bro's happy coding
In our app we are trying to dynamically add fragments to a GridLayout. The empty grid layout is defined in XML as is the layout for the fragment. At run time we examine some data and from that determine the number of fragments to add to the layout as well as which layout to use for each fragment. When we have the fragment assign a size to its generated view it all works, however if we specify the size in the layout file for the fragment nothing shows up in the grid layout. Obviously we could simply specify the size when we create the view but we would prefer to do it in the xml layouts for the fragments because that would allow us to take advantage of Android's built in system for selecting the correct layouts for each device.
I am using support library fragments. I am NOT using support library GridLayout if that makes a difference
The relevant code and xml follows:
The GridLayout XML:
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android">
<ScrollView
android:id="#+id/grid_scroll"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/bottom_fragment"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginRight="8dp"
android:layout_marginTop="?android:attr/actionBarSize"
android:overScrollMode="ifContentScrolls" >
<GridLayout
android:id="#+id/grid"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:alignmentMode="alignMargins"
android:animateLayoutChanges="true"
android:columnCount="3"
android:columnOrderPreserved="true"
android:orientation="horizontal"
android:overScrollMode="ifContentScrolls"
android:rowOrderPreserved="true" >
</GridLayout>
</ScrollView>
</merge>
An Example of the Fragment XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="200dp"
android:layout_height="100dp"
android:alpha="1" >
<Button
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:alpha="1.0" />
</RelativeLayout>
The Fragment onCreateView() Method
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view;
GridLayout.Spec rowSpec = GridLayout.spec(mRowStart, mRowSpan);
GridLayout.Spec columnSpec;
GridLayout.LayoutParams childParams;
if (large) {;
view = inflater.inflate(R.layout.my_place_large, container, false);
columnSpec = GridLayout.spec(mColumnStart, 2);
childParams = new GridLayout.LayoutParams(rowSpec, columnSpec);
//childParams.width = 200; //If I do this everything works regardless of the layout size
} else {
view = inflater.inflate(R.layout.my_place_small, container, false);
columnSpec = GridLayout.spec(mColumnStart, 1);
childParams = new GridLayout.LayoutParams(rowSpec, columnSpec);
//childParams.width = 100; //If I do this everything works regardless of the layout size
}
childParams.setMargins(0, 0, 0, 0);
//childParams.height = 100; //If I do this everything works regardless of the layout size
view.setLayoutParams(childParams);
view.setId(ID);
return view;
}
To Add Fragments to the Layout
private void populateGrid() {
RelativeLayout gridParent = (RelativeLayout) mParentActivity.findViewById(R.id.locations);
mLocationsGrid = (GridLayout) gridParent.findViewById(R.id.grid);
nColumns = mLocationsGrid.getColumnCount();
mAdapter = new MyAdapter(mContext, this, mResolver); //This is how I keep track of the various fragments depending on my app's state
int nCards = mAdapter.getNumberOfCards();
FragmentManager fragmentManager = mParentActivity.getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
for (int i = 0; i < nCards; ++i) {
fragmentTransaction.add(mLocationsGrid.getId(), mAdapter.getFragmentAtIndex(i), String.valueOf(i));
}
fragmentTransaction.commit();
mPopulated = true;
}
I think that should cover it. Just to reiterate, if I uncomment the lines which explicitly set the dimension in onCreateView(), they show up properly in GridLayout so I know everything that keeps track of the fragments and such works, as does the fragment transaction. The issue comes when I try and specify the size in the fragment's xml in which case I get a blank screen.
You thoughts, suggestions and musings are appreciated.
Thanks,
Jared
This is coming very late, but in the off chance this may still be of use. The problem is that you are overriding the XML layout parameters when you dynamically set the new LayoutParams. IE, when you do:
view.setLayoutParams(childParams);
This will erase the XMLs original height and width setting. Just because you are leaving the childParams width/height blank in code doesn't mean a value is not set. In a GridLayout's case, they are set to undefined.
The fix would be to first save the View's existing LayoutParam's height/width and use that when creating the new LayoutParam dynamically. Example:
if (large) {;
view = inflater.inflate(R.layout.my_place_large, container, false);
ViewGroup.LayoutParams oldParams = view.getLayoutParams();
columnSpec = GridLayout.spec(mColumnStart, 2);
childParams = new GridLayout.LayoutParams(rowSpec, columnSpec);
childParams.width = oldParams.width;
}
That will allow you to keep the width/height in XML while applying the row/col specs in code.
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.