I have a FrameLayout with a few buttons, and some ImageViews. When I add a fragment, it shows on top of the ImageViews as expected but below the buttons but I don't know why.
I searched through a lot of the SO posts but couldn't find problems similar to mine.
I have a custom onClickListener that adds the fragment
Custom clickListener class:
public void onClick(View v) {
// a context is passed to the listener
// this gets rootview id
int id= ((ViewGroup)((Activity)context).getWindow().getDecorView().findViewById(android.R.id.content)).getChildAt(0).getId();
MyFragment myFragment = new MyFragment();
FragmentTransaction ft = ((Activity) context).getFragmentManager().beginTransaction();
ft.add(id, myFragment, "F1");
ft.commit();
}
The View I am adding the fragment to:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/startscreen"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/gamelogo"
android:id="#+id/logo"
android:scaleType="fitStart"
android:adjustViewBounds="true"
/>
</FrameLayout>
Activity:
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.startmenu);
final FrameLayout r = (FrameLayout) findViewById(R.id.startscreen);
addViews(r);
}
public void addViews(FrameLayout r){
// add some buttons to r
// add custom OnClickListener to one of the buttons
// add some ImageViews
// add animation to one button
}
FrameLayout is designed to block out an area on the screen to display a single item. Generally, FrameLayout should be used to hold a single child view, because it can be difficult to organize child views in a way that's scalable to different screen sizes without the children overlapping each other.
That's from the Docs, did you considered to change the layout?
I figured that I have to add the fragment to the parent of the base FrameLayout. I don't know why I would have to do that though.
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.
I am trying to make a Button which will always be on standby like Floating Action button despite whatever context it may be in but shall sustain all above my activities, How could I achieve this please refer me a link or give me an idea.
One solution is to create a single activity with the button and then use fragments instead of the current activities.
class ActivityOne extends BaseActivity{
#Override
protected View childView(){
return getLayoutInflator().inflate(R.layout.activity_one, null);
}
}
class ActivityTwo extends BaseActivity{
#Override
protected View childView(){
return getLayoutInflator().inflate(R.layout.activity_two, null);
}
}
public abstract class BaseActivity extends Activity{
protected abstract View childView();
#Override
protected void onCreate(SavedInstanceState savedInstanceState){
super.onCreate(savedInstanceState);
RelativeLayout baseLayout;
ViewStub stub;
baseLayout = (RelativeLayout)
this.getLayoutInflater().inflate(R.layout.layout_base, null);
stub = (ViewStub) baseLayout.findViewById(R.id.base_content_stub);
// Replace viewstub with content.
baseLayout.removeView(stub);
baseLayout.addView(childView(), stub.getLayoutParams());
super.setContentView(baseLayout);
}
}
layout_base.xml
<RelativeLayout
....
>
<ViewStub
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:id="#+id/base_content_stub"/>
<Button
.... // <---- common to all activities
/>
</RelativeLayout>
Your best bet would probably be to make an abstract activity that contains that button and adds it to the layouts of all activity that inherit from it. That way you don't have to duplicate the code in every activity.
It's not possible to use the same button for every activity. You could use the same layout, but you'd have to create the button anew every time you created a new activity. You might be able to avoid that if you did some fancy stuff with the action bar that is frankly not worth it. I suggest you look at using fragments instead of activities, in which case you can have your layout file for you activity look something like this:
<LinearLayout android:id="#+id/fragment_container"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="coop.nisc.intern2016.ui.MainActivity">
<Button
android:id="#+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="#string/button_text" />
<RelativeLayout
android:id="fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Then, you can use a FragmentManager to put the fragment into the fragment_container. The code could look something like this:
private void showCustomFragment() {
FragmentManager fragmentManager = getSupportFragmentManager();
customFragment = new customFragment();
fragmentManager.beginTransaction()
.replace(R.id.fragment_container, customFragment, customFragment.TAG)
.commit();
}
Create a BaseActivity class as a usual activity and a corresponding xml layout file with any layout you want. Add your button inside this layout, and a FrameLayout below the button. Code your button inside the onCreate() of the above activity. Your button's done.
Now, make all your other activities extend the BaseActivity, the super.onCreate() will take care of the button. Instead of setContentView() use:
FrameLayout contentFrameLayout = (FrameLayout) findViewById(R.id.content_frame); //Remember this is the FrameLayout area within your base activity xml
getLayoutInflater().inflate(R.layout.the_layout_you_want_to_load, contentFrameLayout);
'the_layout_you_want_to_load'
is the layout xml of your current activity.
I am having a custom DialogFragment which contains a layout, some UI elements, and a Fragment holder layout. What I need to do is inflate a Content fragment into the holder layout and provide a navigation inside that. On clicking a button inside the added fragment the view will navigate to another view. The fragment will be replaced by another one in the same holder i.e. the contentFragment1 will show some data and on clicking a preview button there will replace contentFragment1 with contentFragment2.
I read somewhere that you cannot replace a fragment hardcoded to the xml with another one.
So I am trying to add the contentFragment1 to the viewholder from the onActivityCreated() of the dialog fragment. But I am getting an error that the resource pointed by R.id.fragmentHolder not found. What could be the possible reason?
Here is my code for the DialogFragment:
public class MyDialog extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog customDialog = new Dialog(getActivity());
customDialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
customDialog.setContentView(R.layout.reports_dialog);
return customDialog;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
android.app.FragmentTransaction fragmentTransaction =getFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.myFragmentHolder, new ReportsListFragment());
fragmentTransaction.commit();
super.onActivityCreated(savedInstanceState);
}
<?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="400dp"
android:background="#android:color/transparent" >
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:text="This is my header text view for the Dialog"
android:textSize="18sp" />
<RelativeLayout
android:id="#+id/myFragmentHolder"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/headerlayout" >
</RelativeLayout>
After trying a lot, I came to a conclusion that onCreateDialog() doesn't have a view, it just sets a view on calling setView().
That is why on adding dynamic(framelayout tag) or static fragment(fragment tag) in the layout of the dialogfragment gives no parent view or duplicate id error.
To achieve the above, one should use onCreateView with a framelayout tag which can be inflated dynamically. Title and alert buttons are then added to the layout.
R.id.myFragmentHolder is inflated to the dialog's layout, and getFragmentManager() returns the manager for the activity, so it can't find the view.
With nested fragments in API level 17 you can use getChildFragmentManager().
Just be sure that the reports_dialog layout containts a layout whose id myFragmentHolder like this one
<FrameLayout
android:id="#+id/fragment_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Just for reference here, as Brandon mention the correct answer is to use the getChildFragmentManager(), keeping in mind, that android will also restore the state of fragments.
The correct code, to add your first fragment, is:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// if the saved instance isn't null, the fragment state will be restored by android
if (savedInstanceState == null) {
getChildFragmentManager().beginTransaction().add(R.id.myFragmentHolder, new ReportsListFragment()).commit();
}
}
after the view has been added. Later use replace if only one fragment should be shown at the same time.
I would also recommend to call transaction.addToBackStack(null); if the Android back button should be supported.
id of fragment holder in layout is fragmentHolder and you are using myFragmentHolder in code try to replace this by:
fragmentTransaction.add(R.id.fragmentHolder, new ReportsListFragment());
I tried to replace a Fragment in FragmentActivity run-time.
fragment_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent" />
MyFragmentActivity.java
public class MyFragmentActivity extends SlidingFragmentActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_activity);
}
// Will be called by AsyncTaskLoader's onLoadFinished.
public void selectActiveContent() {
// MyFragment's top level is LinearLayout
Fragment fragment = new MyFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.content, fragment).commitAllowingStateLoss();
}
However, I realize the outcome is not optimized.
I realize the FrameLayout supplied through my own fragment_activity.xml, is being attached to another parent FrameLayout.
Instead of
FrameLayout
FrameLayout
LinearLayout
LinearLayout
ListView
I wish to have
FrameLayout
LinearLayout
LinearLayout
ListView
May I know how I can achieve so? Is it possible I can have a fragment_activity.xml without a ViewGroup (FrameLayout) ?
While the <merge> element was specifically designed for removing useless levels of view hierarchy, per this answer, you cannot use merge tags in Fragments and you must instead use a ViewGroup root view as you noticed, the lightest weight (i.e., fastest to render) being a FrameLayout.
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.