Search code examples
androidxmlandroid-fragmentsactionbarsherlocktaps

Getting a view from XML file using onCreateView


I am using SherlockFragment to create some taps on my app. So, I reached at this step where I want to get a view from my XML file because I am using onCreateView method to get a view(Text View) in the fragment.

I am currently using this code below to get a view and it is working:

        @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        TextView northingText = new TextView(getActivity());
        northingText.setText("Northing");

        RelativeLayout layout = new RelativeLayout(getActivity()); 
        layout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
        //layout.setGravity(Gravity.CENTER);
        layout.addView(northingText);
        return layout;
    }

However, I want to use the RelativeLayout to be linked directly to my XML file so that I get the view.. IE: RelativeLayout layout = new RelativeLayout(My Xml relativeLayout)

The XML file below

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:padding="4dip"
    android:id="@+id/Layout"
    android:gravity="center_horizontal"
    android:layout_width="match_parent" android:layout_height="match_parent">
  <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="31dp"
        android:text="@string/northing"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textStyle="bold" />

Solution

  • If i understood you correctly you want to use the xml layout above in your fragment.. use following method: Place the xml file in layout folder of res.. build your code.. access it in activity via autogenerated R.java and inflate it in oncreateView of fragment

       View myFragmentView = inflater.inflate(R.layout.fragmentlayout, container, false);
    
       return myFragmentView;
    

    here fragmentlayout is the name of layout with above xml... and return that in oncreateView ...