I have a simple Android app. The layout folder shows an activity_main.xml file and a fragment_main.xml file. In that fragment.xml file I have placed a button that I've named buttonTest.
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.snapvest.thunderbird.app.MainActivity$PlaceholderFragment">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TEST"
android:id="#+id/buttonTest"
android:layout_gravity="center_horizontal" />
</LinearLayout>
in the MainActivity.java file I'm trying to gain access to that buttonTest.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
// Get access to the buttons
final Button buttonTest = (Button)findViewById(R.id.buttonTest);
}
It compiles just fine. But when I run it the buttonTest variable comes back as a null pointer.
Why is it not finding the buttonTest object?
I think I found the solution. MainActivity.java sets up the activity_main.xml which then uses fragment_main.xml as its (initially) single, primary fragment. That's why we are supposed to actually put all of our UI for the activity primarily in fragment_main.xml (and actually put NOTHING in activity_main.xml).
Near the bottom of MainActivity.java there is a section that initializes the fragment_main.xml. And it is THERE that I need to gain access to the buttons and other objects of the UI for the fragment. Such as:
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
// Get access to the buttons
final Button buttonAvailableOptions = (Button)rootView.findViewById(R.id.buttonAvailableOptions);
return rootView;
}
}
Most of that, above, is automatically added by Android Studio. The part starting with "Get access to the button" is mine and is where you set up any access to or processing of the buttons and other UI objects.
The reason why findViewById() is failing to find the button is because setContentView() primes findViewById() to only look in the layout.xml file you gave to setContentView(), and your button is not located in R.layout.activity_main. If your button is located in the Fragment (which it appears to be) then you should be accessing and manipulating it from the Fragment, not the Activity. This ensures that your Activity and Fragment logic stay decoupled, allowing you to re-use the Fragment with different Activities.
You can use like this.
final Button buttonAvailableOptions = getActivity().findViewById(R.id.buttonAvailableOptions);
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'm trying to develop a sign-up menu for a social app, that I'm working on. I would like the sign-up menu to consist of a PageViewer, which holds five fragments. The last three fragments contains a ListView, where the user can 'check' information about them selves. The XML is here:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:minWidth="25px"
android:minHeight="25px"
android:id="#+id/layoutSignupLists">
<TextView
android:text="Add something here"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:id="#+id/signupListDescription" />
<ListView
android:id="#+id/interestListView"
android:layout_below="#id/signupListDescription"
android:layout_height="match_parent"
android:layout_width="match_parent" />
</RelativeLayout>
This layout is inflated, when the last three fragments are created as is displayed correctly. I have subscribed a delegate to the itemSelected event in the ListView as seen below:
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
//Inflate view and find content
View view = inflater.Inflate(Resource.Layout.signupFragLayout4, container, false);
interestListView = view.FindViewById <ListView>(Resource.Id.interestListView);
var desc = view.FindViewById<TextView>(Resource.Id.signupListDescription);
//Adds the description
desc.Text = GetString(Resource.String.profile_menu_edit_interests);
//Populate ListView
interestListView.Adapter = new ArrayAdapter<string>(Activity,
Resource.Layout.CheckedListViewItem, MainActivity.InfoNames[(int)InfoType.Interest]);
interestListView.ChoiceMode = ChoiceMode.Multiple;
interestListView.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) =>
{
if(!Interests.Contains(e.Position))
Interests.Add(e.Position);
else
Interests.Remove(e.Position);
};
return view;
}
When putting a break-point in the delegate I find that it's never called and thus the ListView reset upon swiping right or left.
How can I make the fragment 'hold on' to the information so that it's displayed every time the fragment is shown?
Place the information in the MainActivity. You can make a simple reference to it by putting this variable in your fragment class:
MainActivity mainActivity;
And in your OnCreateView() place this to initialize it:
mainActivity = (MainActivity)Activity;
Now if you have any public variables in the mainActivity, you can reference them in the fragment like:
textView.Text = mainActivity.VariableName;
Additionally, for putting the information back in the fragment, override the 'OnResume' method like so:
public override void OnResume()
{
base.OnResume();
//Code to fill in all the information in your fragment again. I.E:
textView.Text = mainActivity.VariableName;
}
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
I am working on android app and am trying to get fragments working but I've run into a problem.
When the app launches it loads an activity which is supposed to house the two fragments. Fragment1 contains a list of stored logins and fragment 2 will show the details associated with that login.
The list fragment is supposed to retrieve data from the SQLite database and display on the screen and once the item is clicked, it loads the second fragment, but I am having problem getting the first stage working.
In my main activity class I have the following.
public class PasswordListMain extends Activity {
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.password_management);
}
}
The password_management XML file contains the following
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<fragment
android:id="#+id/passwordList"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.BoardiesITSolutions.PasswordManager.PasswordListFrag">
</fragment>
</LinearLayout>
It just contains the fragment as this is the portrait screen, I thought I'd get this bit working before getting it working side by side.
The PasswordListFrag contains the following
public class PasswordListFrag extends ListFragment{
Common common;
com.BoardiesITSolutions.logic.ManagePasswordList managePasswordList;
ArrayList<String> savedPassword;
TextView txtNoRecords;
ListView myListView;
ArrayAdapter<Spanned> passwordArrayAdapter;
AdView adView;
#Override
public View onCreateView(LayoutInflater inflator, ViewGroup container, Bundle savedInstanceState)
{
View view = inflator.inflate(R.layout.password_list, container, false);
myListView = getListView();
common = new Common(getActivity().getApplicationContext());
//AdView adView = (AdView)findViewById(R.id.adView);
common.requestAdvert(adView);
managePasswordList = new ManagePasswordList(getActivity().getApplicationContext());
//txtNoRecords = (TextView)findViewById(R.id.password_noRecords);
populateListArray();
common.showToastMessage("Adapter updated", Toast.LENGTH_LONG);
//myListView.setOnItemClickListener(mListView);
return view;
}
private void populateListArray()
{
ArrayList<Spanned> passwords = managePasswordList.getPasswordList();
if (passwords != null && passwords.size() > 0)
{
passwordArrayAdapter = new ArrayAdapter<Spanned>(getActivity().getApplicationContext(),
android.R.layout.simple_list_item_1, passwords);
setListAdapter(passwordArrayAdapter);
passwordArrayAdapter.setNotifyOnChange(true);
myListView.setTextFilterEnabled(true);
txtNoRecords.setVisibility(View.GONE);
}
else
{
txtNoRecords.setVisibility(View.VISIBLE);
}
}
}
Below is the XML for the list fragment
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView android:id="#+id/password_noRecords"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_gravity="center"
android:text="There are currently\nno saved logins"
android:textSize="20dp"
android:textStyle="bold|italic"/>
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#+id/adView">
</ListView>
<com.google.ads.AdView android:id="#+id/adView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
ads:adUnitId="5555555"
ads:adSize="BANNER"
android:layout_alignParentBottom="true">
</com.google.ads.AdView>
</RelativeLayout>
When the app loads it instantly crashes when it tries to load this screen.
The error is
java.lang.RuntimeException: Unable to start activity ComponentInfo
PasswordListMain: android.view.InflatException: Binary XML file line
#7 Error inflating class fragment
I have no idea what's causing this or how to fix the problem.
Thanks for any help you can provide.
My best guess for the issue is this line (but admittedly I'm unsure):
myListView = getListView();
You're calling it before the fragment has a view - and I don't think that will work too well. I would recommend doing your initialization work of the views involved in onActivityCreated() instead of in onCreateView() and the other components (like your data store thing and Common) in onCreate()
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.