0

I am just learning fragment now, and write a simple project hope to add fragment into MainActivity by java code. But not insert xml into main_activity.xml.

But after I finish the code, it cannot run on device, just alert "application stoped".

Here is my code:

  1. MainActivity.java

    package com.example.dynamicfragment;
    
    import android.os.Bundle;
    import android.annotation.SuppressLint;
    import android.app.Activity;
    import android.app.FragmentManager;
    import android.app.FragmentTransaction;
    import android.view.Menu;
    
    public class MainActivity extends Activity {
    
    
    @SuppressLint("NewApi")
    @Override
     protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    
    
    ButtonList buttonlist_fragment = new ButtonList(); // instanciate a new view of ButtonList
    
    FragmentManager fragment_manager= getFragmentManager(); //fragment manager and fragment transaction
    FragmentTransaction fragment_transaction = fragment_manager.beginTransaction();     
    fragment_transaction.add(R.id.layoutToReplace, buttonlist_fragment);
    fragment_transaction.commit();
    }
    
       }
    
  2. activity_main.xml

     <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:paddingBottom="@dimen/activity_vertical_margin"
     android:paddingLeft="@dimen/activity_horizontal_margin"
     android:paddingRight="@dimen/activity_horizontal_margin"
     android:paddingTop="@dimen/activity_vertical_margin"
     tools:context=".MainActivity" >
    
    <LinearLayout 
    android:id="@+id/layoutToReplace"
    android:orientation="vertical">
    
    </LinearLayout>
    </RelativeLayout>
    
  3. Fragment class:

     @SuppressLint("NewApi")
     public class ButtonList extends Fragment {
    
     public View onCreateView(LayoutInflater inflater, ViewGroup Container, Bundle savedInstanceState){
    
    //return inflate layout for this fragment
    return inflater.inflate(R.layout.button_list_fragment_layout, Container,false);
    
       } 
       } 
    
  4. Fragment XML layout:

      <?xml version="1.0" encoding="UTF-8"?>
      <Linerlayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="fill_parent"
       android:layout_height="fill_parent"
      >
    
      <Button
      android:id="@+id/Student"
      android:layout_width="150dip"
      android:layout_height="wrap_content"
      android:layout_marginTop="50dip"
      android:text="Student"
      />
      <Button
      android:id="@+id/Documents"
      android:layout_width="150dip"
      android:layout_height="wrap_content"
      android:text="Documents"
      />
      </Linerlayout>
    

log cat

03-27 12:22:21.913: D/AndroidRuntime(23764): Shutting down VM
03-27 12:22:21.913: W/dalvikvm(23764): threadid=1: thread exiting with uncaught exception (group=0x40b2c1f8)
03-27 12:22:21.976: E/AndroidRuntime(23764): FATAL EXCEPTION: main
03-27 12:22:21.976: E/AndroidRuntime(23764): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.dynamicfragment/com.example.dynamicfragment.MainActivity}: java.lang.RuntimeException: Binary XML file line #11: You must supply a layout_width attribute.
03-27 12:22:21.976: E/AndroidRuntime(23764):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1968)
03-27 12:22:21.976: E/AndroidRuntime(23764):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1993)
03-27 12:22:21.976: E/AndroidRuntime(23764):    at android.app.ActivityThread.access$600(ActivityThread.java:127)
03-27 12:22:21.976: E/AndroidRuntime(23764):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1151)
03-27 12:22:21.976: E/AndroidRuntime(23764):    at android.os.Handler.dispatchMessage(Handler.java:99)
03-27 12:22:21.976: E/AndroidRuntime(23764):    at android.os.Looper.loop(Looper.java:137)
03-27 12:22:21.976: E/AndroidRuntime(23764):    at android.app.ActivityThread.main(ActivityThread.java:4499)
03-27 12:22:21.976: E/AndroidRuntime(23764):    at java.lang.reflect.Method.invokeNative(Native Method)
03-27 12:22:21.976: E/AndroidRuntime(23764):    at java.lang.reflect.Method.invoke(Method.java:511)
03-27 12:22:21.976: E/AndroidRuntime(23764):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
03-27 12:22:21.976: E/AndroidRuntime(23764):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:558)
03-27 12:22:21.976: E/AndroidRuntime(23764):    at dalvik.system.NativeStart.main(Native Method)
03-27 12:22:21.976: E/AndroidRuntime(23764): Caused by: java.lang.RuntimeException: Binary XML file line #11: You must supply a layout_width attribute.
03-27 12:22:21.976: E/AndroidRuntime(23764):    at android.content.res.TypedArray.getLayoutDimension(TypedArray.java:491)
03-27 12:22:21.976: E/AndroidRuntime(23764):    at android.view.ViewGroup$LayoutParams.setBaseAttributes(ViewGroup.java:5318)
03-27 12:22:21.976: E/AndroidRuntime(23764):    at android.view.ViewGroup$MarginLayoutParams.<init>(ViewGroup.java:5439)
03-27 12:22:21.976: E/AndroidRuntime(23764):    at android.widget.RelativeLayout$LayoutParams.<init>(RelativeLayout.java:1154)
03-27 12:22:21.976: E/AndroidRuntime(23764):    at android.widget.RelativeLayout.generateLayoutParams(RelativeLayout.java:1021)
03-27 12:22:21.976: E/AndroidRuntime(23764):    at android.widget.RelativeLayout.generateLayoutParams(RelativeLayout.java:72)
03-27 12:22:21.976: E/AndroidRuntime(23764):    at android.view.LayoutInflater.rInflate(LayoutInflater.java:741)
03-27 12:22:21.976: E/AndroidRuntime(23764):    at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
03-27 12:22:21.976: E/AndroidRuntime(23764):    at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
03-27 12:22:21.976: E/AndroidRuntime(23764):    at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
03-27 12:22:21.976: E/AndroidRuntime(23764):    at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:262)
03-27 12:22:21.976: E/AndroidRuntime(23764):    at android.app.Activity.setContentView(Activity.java:2007)
03-27 12:22:21.976: E/AndroidRuntime(23764):    at com.example.dynamicfragment.MainActivity.onCreate(MainActivity.java:18)
03-27 12:22:21.976: E/AndroidRuntime(23764):    at android.app.Activity.performCreate(Activity.java:4637)
03-27 12:22:21.976: E/AndroidRuntime(23764):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1051)
03-27 12:22:21.976: E/AndroidRuntime(23764):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1932)
03-27 12:22:21.976: E/AndroidRuntime(23764):    ... 11 more
03-27 12:22:25.929: I/Process(23764): Sending signal. PID: 23764 SIG: 9
Raghunandan
  • 132,755
  • 26
  • 225
  • 256
  • I think i deleted the imports for fragment while editing by mistake. DO check whether the imports are from support library or not coz that could also cause problems – Raghunandan Mar 27 '14 at 16:28

3 Answers3

0

Your 'main activity xml layout' contains a LinearLayout tag without necessary attributes - layout_width, layout_height.

Set them to match_parent, or whatever:

<RelativeLayout ... >

<LinearLayout 
    android:id="@+id/layoutToReplace"
    android:orientation="vertical"

    android:layout_width="match_parent"
    android:layout_height="match_parent"/>
</RelativeLayout>

Strange, though,that you feed your MainActivity such a layout, considering it will host a Fragment. Typically, FrameLayout is used for such purpose. Consider reading this

Drew
  • 3,307
  • 22
  • 33
0

You need to specify the layout width and height for the LinearLayout.

But Looking at the activity_main.xml there is no need for both RelativeLayout and LinearLayout. You can use any one of those (LinaerLayout/RelativeLayout) as ViewGroup. Generally FrameLayout is used.

In activity_main.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:id="@+id/layoutToReplace"
    android:layout_height="match_parent" >

</FrameLayout>

Secondly you have @SuppressLint("NewApi"). The lint tool gives you a hint that some of the features are available in new api's only and you need to check your manifest file for min sdk version to check for compatibility.

I am guessing your min sdk is below api level 11. Check in manifest

Thirdly fill_parent is deprecated use match_parent

Quoting docs

fill_parent (renamed match_parent in API Level 8) tells your view to become as big as its parent view group will allow.

<Linerlayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
Raghunandan
  • 132,755
  • 26
  • 225
  • 256
0

What do u mean by #2 and #4? What was the LogCat error it gave u??

What line was the error at?

JAVA= MainActivity=

    onCreate () {
setContentView(R.layout.frag_vocablist); 
    }

    public void onItemSelected(String id) {
    Bundle arguments = new Bundle();
    arguments.putString(“FragmentB_package”, id);


    FragmentB fragment = new FragmentB();
    fragment.setArguments(arguments);
    getSupportFragmentManager().beginTransaction().replace(R.id.item_detail_container, fragment).commit();
}

R.layout.frag_vocablist. Inside your XML layout for your MainActivity.java include=

   <fragment
        android:id="@+id/vocab_list"
        android:name="com.gene.yourPackageName.Frag_JavaClass"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        tools:layout="@android:layout/list_content" />

android:name="com.gene.yourPackageName.Frag_JavaClass" calls the Java file Frag_JavaClass. Inside Frag_JavaClass you need to set:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);
        if (savedInstanceState != null
                && savedInstanceState.containsKey(STATE_ACTIVATED_POSITION)) {
            setActivatedPosition(savedInstanceState
                    .getInt(STATE_ACTIVATED_POSITION));
        }
        mView = inflater.inflate(R.layout.frag_abc_sort, container, false);
        mABCListView = (IndexableListView) mView.findViewById(R.id.frag_abc);
        //...
        return mView;
    }

    public void replaceFrag(String[] List, boolean SetABCListScrollable) {
        mABCListView.setFastScrollEnabled(true);
        mABCListView.showList(SetABCListScrollable);
        ContentAdapter adapter = new ContentAdapter(mView.getContext(),
                android.R.layout.simple_list_item_1, List);
        mABCListView.setAdapter(adapter);
    }

R.layout.frag_abc_sort= XML Layout for Frag_JavaClass.java

<com.gene.android.Frag_JavaClass.IndexableListView
    android:id="@+id/frag_abc"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" />

If you still don't get it, check my comment here: How to pass data between fragments

Community
  • 1
  • 1
Gene
  • 10,819
  • 1
  • 66
  • 58