17

编辑 ::: 请参考下面我的回答...

问题:::

我对在 Android 中使用 Fragments 非常陌生,我完全搞砸了。

我只是想构建一个使用片段的简单示例应用程序。我的情况是,我的主要活动中有两个片段。第一个片段有一个编辑文本和一个按钮。第二个片段有一个文本视图。当我在编辑文本中输入名称并单击按钮时,第二个片段中的文本视图应显示在第一个片段的编辑文本中输入的名称。

我正在使用片段的静态分配(在 XML 中分配片段)。

请参阅下面的 XML 文件和代码...

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 文件 :::

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;
        }

    }

片段_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;


    }

}

片段_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);
    }

}

当我运行应用程序时,有很多异常.. 这是 logcat 跟踪..

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

我已经看到了有关如何执行此操作的示例,但无法弄清楚。请指出我做错的地区,也请张贴正确的做法。

非常感谢您的时间...

编辑 :::

我已更改 MainActivity.java 以扩展 FragmentActivity 而不是 Activity 并且还更改了 activity_main.xml 中的 android:name 值以指向 Java 文件而不是片段...

我得到以下异常:::

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 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
04-16 15:29:43.821: E/AndroidRuntime(563):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
04-16 15:29:43.821: E/AndroidRuntime(563):  at dalvik.system.NativeStart.main(Native Method)
04-16 15:29:43.821: E/AndroidRuntime(563): Caused by: android.view.InflateException: Binary XML file line #5: Error inflating class fragment
04-16 15:29:43.821: E/AndroidRuntime(563):  at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:688)
04-16 15:29:43.821: E/AndroidRuntime(563):  at android.view.LayoutInflater.rInflate(LayoutInflater.java:724)
04-16 15:29:43.821: E/AndroidRuntime(563):  at android.view.LayoutInflater.inflate(LayoutInflater.java:479)
04-16 15:29:43.821: E/AndroidRuntime(563):  at android.view.LayoutInflater.inflate(LayoutInflater.java:391)
04-16 15:29:43.821: E/AndroidRuntime(563):  at android.view.LayoutInflater.inflate(LayoutInflater.java:347)
04-16 15:29:43.821: E/AndroidRuntime(563):  at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:223)
04-16 15:29:43.821: E/AndroidRuntime(563):  at android.app.Activity.setContentView(Activity.java:1786)
04-16 15:29:43.821: E/AndroidRuntime(563):  at com.example.fragmentexample.MainActivity.onCreate(MainActivity.java:13)
04-16 15:29:43.821: E/AndroidRuntime(563):  at android.app.Activity.performCreate(Activity.java:4397)
04-16 15:29:43.821: E/AndroidRuntime(563):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1048)
04-16 15:29:43.821: E/AndroidRuntime(563):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1779)
04-16 15:29:43.821: E/AndroidRuntime(563):  ... 11 more
04-16 15:29:43.821: E/AndroidRuntime(563): Caused by: java.lang.ClassCastException: com.example.fragmentexample.Fragment_1 cannot be cast to android.support.v4.app.Fragment
04-16 15:29:43.821: E/AndroidRuntime(563):  at android.support.v4.app.Fragment.instantiate(Fragment.java:394)
04-16 15:29:43.821: E/AndroidRuntime(563):  at android.support.v4.app.Fragment.instantiate(Fragment.java:369)
04-16 15:29:43.821: E/AndroidRuntime(563):  at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:272)
04-16 15:29:43.821: E/AndroidRuntime(563):  at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:660)
04-16 15:29:43.821: E/AndroidRuntime(563):  ... 21 more

这是 activity_main.xml 更改后的 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="fill_parent"
        android:layout_height="fill_parent" >
    </fragment>

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

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

</LinearLayout>
4

4 回答 4

14

Okie...终于找到了解决方案。大概,变化不大。

看看下面的代码...

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>

fragment_fragment_1 和 fragment_fragment_2 的布局保持不变。

片段_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;


        }

    }

片段_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);
    }

}

这是屏幕截图...

在此处输入图像描述

于 2013-04-16T10:20:37.313 回答
2

您需要向 Fragments 添加一个空的公共构造函数,就像堆栈跟踪中所说的那样:

public class Fragment_2 extends Fragment{

    public Frament_2() {
        //BLAH!
    }

    // The rest of your code

}
于 2013-04-16T09:45:35.147 回答
2

这是两个 Fragment 之间通信的经典案例。
但让我们先介绍更基本的东西。

碎片的骨架

第一个片段

编辑文本
按钮

public class FirstFragment extends Fragment{

      private EditText editext;
      private Button button;

      public static FirstFragment getInstance(){  
           return new FirstFragment();
      }

      public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle bundle){
           View view = inflater.inflate(R.Layout.fragment1,parent,false);
           editext = (EditText)view.findViewById(R.id.editText)
           button = (Button)view.findViewById(R.id.button)
           return view;               

      }

}

第二片段

文本视图

public class SecondFragment extends Fragment{

      private TextView textView;

      public static SecondFragment getInstance(){  
           return new SecondFragment();
      }

      public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle bundle){
           View view = inflater.inflate(R.Layout.fragment2,parent,false);
           textView = (TextView)view.findViewById(R.id.editText)
           return view;               

      }

      public void showMessage(String msg)
      {
           textView.setText(msg)
      }

}

如何创建片段实例

FirstFragment fragmne1 = FirstFragment.getInstance();
SecondFragment fragmne1 = SecondFragment.getInstance();

如何在活动中添加它们?

getSupportFragmentManager()
         .beginTransaction()
         .add(R.id.placeholder1,fragment1,"TAG1")
         .add(R.id.placeholder2,fragment2,"TAG2")
         .commit();

现在是通讯部分

创建接口

public interface FragmentListener{
     public void buttonClicked();
}

在Activity中实现这个接口并覆盖方法

public MyActivity extends AppcompatActivity implements MyFragmentListener{

     @Override
     public void buttonClicked(){
          fragment2.showMessage(String msg);
     }

}

从 Fragment 发送数据

  1. 在 FirstFragment 中初始化监听器
  2. 在按钮单击时调用接口方法。

FirstFragment 的最终结构

public class FirstFragment extends Fragment{

      private EditText editext;
      private Button button;
      private MyFragmentListener listener;

      public static FirstFragment getInstance(){  
           return new FirstFragment();
      }

      public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle bundle){
           View view = inflater.inflate(R.Layout.fragment1,parent,false);
           editext = (EditText)view.findViewById(R.id.editText)
           button = (Button)view.findViewById(R.id.button)

           // button click method 
           listener.buttonClicked(editText.getText().toString());

           return view;               

      }

      @Override 
      public void onAttach(Context context){
           listener = (MyFragmentListener)context;
      }

}
于 2019-01-01T15:32:45.020 回答
1

请按如下方式编辑您的 activity_main.XML AS。

<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"
    class="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"
    class="com.example.fragmentexample.fragment_fragment_2"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <!-- Preview: layout=@layout/fragment_basic -->
</fragment>
</LinearLayout>
于 2013-04-16T10:18:07.457 回答