Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
114 views
in Technique[技术] by (71.8m points)

How to use Fragments in Android

EDIT ::: Please refer to my answer below...

Question:::

I am very new to using Fragments in Android and I am completely messed up.

I am just trying to build a simple sample application that uses Fragments. My scenario is, I have two fragments in my main activity. The first fragment has an edittext and a button. The second fragment has a textview. When I enter a name in the edittext and click on the button, the textview in the second fragment should display the name entered in the edittext of the first fragment.

I am using the static assignment of fragments (assigning fragments in XML).

Please refer to the XML files and Code below...

activity_main.XML

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <fragment
        android:id="@+id/fragment_content_1"
        android:name="com.example.fragmentexample.fragment_fragment_1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >
    </fragment>

    <fragment
        android:id="@+id/fragment_content_2"
        android:name="com.example.fragmentexample.fragment_fragment_2"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

        <!-- Preview: layout=@layout/fragment_basic -->
    </fragment>

</LinearLayout>

fragment_fragment_1.XML

<?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" >

    <EditText
        android:id="@+id/edtxtPersonName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPersonName" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/btnSayHi"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Say Hi" />

</LinearLayout>

fragment_fragment_2.XML

<?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" >

    <TextView
        android:id="@+id/txtViewResult"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="I will say Hi" />

</LinearLayout>

Java Files :::

MainActivity.Java

    public class MainActivity extends Activity {

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.activity_main, menu);
            return true;
        }

    }

Fragment_1.Java

public class Fragment_1 extends Fragment{

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub      

        View view = inflater.inflate(R.layout.fragment_fragment_1, container, false);

        final EditText edtxtPersonName_Fragment = (EditText) view.findViewById(R.id.edtxtPersonName);
        Button btnSayHi_Fragment = (Button) view.findViewById(R.id.btnSayHi);

        btnSayHi_Fragment.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                String name = edtxtPersonName_Fragment.getText().toString();

                FragmentManager fm = getFragmentManager();
                Fragment_2 f2 = (Fragment_2) fm.findFragmentById(R.id.fragment_content_2);

                if(f2 != null && f2.isInLayout())
                {
                    f2.setName(name);
                }

                Activity activity = getActivity();

                if(activity != null)
                {
                    Toast.makeText(activity, "Say&ing Hi in Progress...", Toast.LENGTH_LONG).show();
                }
            }
        });

        return view;


    }

}

Fragment_2.Java

public class Fragment_2 extends Fragment{

    View view;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub

        view = inflater.inflate(R.layout.fragment_fragment_2, container, false);        
        return view;
    }

    public void setName(String name)
    {
        TextView txtName = (TextView) view.findViewById(R.id.txtViewResult);
        txtName.setText("Hi " + name);
    }

}

When I run the application, there are whole lot of exceptions.. Here is the logcat trace..

04-16 15:06:48.781: E/AndroidRuntime(420): FATAL EXCEPTION: main
04-16 15:06:48.781: E/AndroidRuntime(420): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.fragmentexample/com.example.fragmentexample.MainActivity}: android.view.InflateException: Binary XML file line #5: Error inflating class fragment
04-16 15:06:48.781: E/AndroidRuntime(420):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1815)
04-16 15:06:48.781: E/AndroidRuntime(420):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1831)
04-16 15:06:48.781: E/AndroidRuntime(420):  at android.app.ActivityThread.access$500(ActivityThread.java:122)
04-16 15:06:48.781: E/AndroidRuntime(420):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1024)
04-16 15:06:48.781: E/AndroidRuntime(420):  at android.os.Handler.dispatchMessage(Handler.java:99)
04-16 15:06:48.781: E/AndroidRuntime(420):  at android.os.Looper.loop(Looper.java:132)
04-16 15:06:48.781: E/AndroidRuntime(420):  at android.app.ActivityThread.main(ActivityThread.java:4123)
04-16 15:06:48.781: E/AndroidRuntime(420):  at java.lang.reflect.Method.invokeNative(Native Method)
04-16 15:06:48.781: E/AndroidRuntime(420):  at java.lang.reflect.Method.invoke(Method.java:491)
04-16 15:06:48.781: E/AndroidRuntime(420):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
04-16 15:06:48.781: E/AndroidRuntime(420):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
04-16 15:06:48.781: E/AndroidRuntime(420):  at dalvik.system.NativeStart.main(Native Method)
04-16 15:06:48.781: E/AndroidRuntime(420): Caused by: android.view.InflateException: Binary XML file line #5: Error inflating class fragment
04-16 15:06:48.781: E/AndroidRuntime(420):  at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:688)
04-16 15:06:48.781: E/AndroidRuntime(420):  at android.view.LayoutInflater.rInflate(LayoutInflater.java:724)
04-16 15:06:48.781: E/AndroidRuntime(420):  at android.view.LayoutInflater.inflate(LayoutInflater.java:479)
04-16 15:06:48.781: E/AndroidRuntime(420):  at android.view.LayoutInflater.inflate(LayoutInflater.java:391)
04-16 15:06:48.781: E/AndroidRuntime(420):  at android.view.LayoutInflater.inflate(LayoutInflater.java:347)
04-16 15:06:48.781: E/AndroidRuntime(420):  at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:223)
04-16 15:06:48.781: E/AndroidRuntime(420):  at android.app.Activity.setContentView(Activity.java:1786)
04-16 15:06:48.781: E/AndroidRuntime(420):  at com.example.fragmentexample.MainActivity.onCreate(MainActivity.java:12)
04-16 15:06:48.781: E/AndroidRuntime(420):  at android.app.Activity.performCreate(Activity.java:4397)
04-16 15:06:48.781: E/AndroidRuntime(420):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1048)
04-16 15:06:48.781: E/AndroidRuntime(420):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1779)
04-16 15:06:48.781: E/AndroidRuntime(420):  ... 11 more
04-16 15:06:48.781: E/AndroidRuntime(420): Caused by: android.app.Fragment$InstantiationException: Unable to instantiate fragment com.example.fragmentexample.fragment_fragment_1: make sure class name exists, is public, and has an empty constructor that is public
04-16 15:06:48.781: E/AndroidRuntime(420):  at android.app.Fragment.instantiate(Fragment.java:567)
04-16 15:06:48.781: E/AndroidRuntime(420):  at android.app.Fragment.instantiate(Fragment.java:535)
04-16 15:06:48.781: E/AndroidRuntime(420):  at android.app.Activity.onCreateView(Activity.java:4168)
04-16 15:06:48.781: E/AndroidRuntime(420):  at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:664)
04-16 15:06:48.781: E/AndroidRuntime(420):  ... 21 more
04-16 15:06:48.781: E/AndroidRuntime(420): Caused by: java.lang.ClassNotFoundException: com.example.fragmentexample.fragment_fragment_1 in loader dalvik.system.PathClassLoader[/data/app/com.example.fragmentexample-1.apk]
04-16 15:06:48.781: E/AndroidRuntime(420):  at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:251)
04-16 15:06:48.781: E/AndroidRuntime(420):  at java.lang.ClassLoader.loadClass(ClassLoader.java:540)
04-16 15:06:48.781: E/AndroidRuntime(420):  at java.lang.ClassLoader.loadClass(ClassLoader.java:500)
04-16 15:06:48.781: E/AndroidRuntime(420):  at android.app.Fragment.instantiate(Fragment.java:557)
04-16 15:06:48.781: E/AndroidRuntime(420):  ... 24 more

I have seen examples on how to do it, but couldn't figure it out. Please point the regions where i am doing it wrong, and also please post the correct way of doing it.

Thanks a lot for your time...

EDIT :::

I have changed the MainActivity.java to extend FragmentActivity instead of Activity and also changed the android:name values in the activity_main.xml to point to Java Files instead of fragments...

I get the following exceptions :::

04-16 15:29:43.821: E/AndroidRuntime(563): FATAL EXCEPTION: main
04-16 15:29:43.821: E/AndroidRuntime(563): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.fragmentexample/com.example.fragmentexample.MainActivity}: android.view.InflateException: Binary XML file line #5: Error inflating class fragment
04-16 15:29:43.821: E/AndroidRuntime(563):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1815)
04-16 15:29:43.821: E/AndroidRuntime(563):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1831)
04-16 15:29:43.821: E/AndroidRuntime(563):  at android.app.ActivityThread.access$500(ActivityThread.java:122)
04-16 15:29:43.821: E/AndroidRuntime(563):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1024)
04-16 15:29:43.821: E/AndroidRuntime(563):  at android.os.Handler.dispatchMessage(Handler.java:99)
04-16 15:29:43.821: E/AndroidRuntime(563):  at android.os.Looper.loop(Looper.java:132)
04-16 15:29:43.821: E/AndroidRuntime(563):  at android.app.ActivityThread.main(ActivityThread.java:4123)
04-16 15:29:43.821: E/AndroidRuntime(563):  at java.lang.reflect.Method.invokeNative(Native Method)
04-16 15:29:43.821: E/AndroidRuntime(563):  at java.lang.reflect.Method.invoke(Method.java:491)
04-16 15:29:43.821: E/AndroidRuntime(563):  at c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Okie... Finally found a solution. Probably, it wasn't much of a change.

Check out the code below...

activity_main.XML

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <fragment
        android:id="@+id/fragment_content_1"
        android:name="com.example.fragmentexample.Fragment_1"
        android:layout_width="0dip"
        android:layout_weight="0.50"
        android:layout_height="fill_parent" >
    </fragment>

    <fragment
        android:id="@+id/fragment_content_2"
        android:name="com.example.fragmentexample.Fragment_2"
        android:layout_width="0dip"
        android:layout_weight="0.50"
        android:layout_height="fill_parent" >

        <!-- Preview: layout=@layout/fragment_basic -->
    </fragment>

</LinearLayout>

The layouts of fragment_fragment_1 and fragment_fragment_2 remain the same.

Fragment_1.Java

public class Fragment_1 extends Fragment{

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            // TODO Auto-generated method stub      

            View view = inflater.inflate(R.layout.fragment_fragment_1, container, false);

            final EditText edtxtPersonName_Fragment = (EditText) view.findViewById(R.id.edtxtPersonName);
            Button btnSayHi_Fragment = (Button) view.findViewById(R.id.btnSayHi);

            btnSayHi_Fragment.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub

                    String name = edtxtPersonName_Fragment.getText().toString();

                    FragmentManager fm = getFragmentManager();
                    Fragment_2 f2 = (Fragment_2) fm.findFragmentById(R.id.fragment_content_2);

                    if(f2 != null && f2.isInLayout())
                    {
                        f2.setName(name);
                    }

                    Activity activity = getActivity();

                    if(activity != null)
                    {
                        Toast.makeText(activity, "Say&ing Hi in Progress...", Toast.LENGTH_LONG).show();
                    }
                }
            });

            return view;


        }

    }

Fragment_2.Java

public class Fragment_2 extends Fragment{

    View view;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub

        view = inflater.inflate(R.layout.fragment_fragment_2, container, false);        
        return view;
    }

    public void setName(String name)
    {
        TextView txtName = (TextView) view.findViewById(R.id.txtViewResult);
        txtName.setText("Hi " + name);
    }

}

Here is the ScreenShot...

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...