java – How can I define a fragment's layout from XML?-ThrowExceptions

Exception or error:

I’m trying to define a fragment’s layout in XML in the same way that I defined the layout of my view.

Is this possible? I tried several things, but none of them seem to work.

My activity layout looks as follows (main.xml):

<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
  <fragment
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:name="full.lommeregner.Lommeregnerrv2Activity"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/lommeregnerv2">
    </fragment>   

</ListView>

Now, since I’m not a big fan of generating layouts through raw Java code, I tried defining my fragment as follows (fragment_lommeregner.xml):

  <fragment
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:name="full.lommeregner.Lommeregnerrv2Activity"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/lommeregnerv2">
       <!-- my content was located here (some textviews, buttons and so on). -->
    </fragment> 

Am I doing something wrong? How can I define the layout of a fragment through XML?

How to solve:

A Fragment works much like an activity, in that you need a Java class file to go with it. you cannot create a Fragment just by creating a fragment layout – you need a class for your fragment:

  1. Create a layout XML and an Activity subclass for your activity
  2. Create a layout XML and a Fragment subclass for your fragment
  3. Tie the two together in your Activity layout XML (or using FragmentTransaction if you want to do it in Java code)

If you haven’t already done so, read, re-read and digest everything on this page:
https://developer.android.com/guide/components/fragments.html

There’s a lot there, but Fragments are an essential part of Android apps now so it’s required reading. The good news is that the basics of fragments is pretty simple.

###

Simply add into your <fragment> tag as property:

tools:layout="@layout/your_layout_xml"

And in your main.xml (or <fragment> tag container) into your parent container (in this case ListView):

xmlns:tools="http://schemas.android.com/tools"

Leave a Reply

Your email address will not be published. Required fields are marked *