在Activity中调用片段布局

时间:2017-02-10 01:48:35

标签: java android android-fragments

我正在尝试调用一个充当侧栏菜单的片段,但是当我尝试运行我的应用程序时,它说应用程序已停止。我一直在尝试在互联网上找到的所有方法。这是我到目前为止所做的。

activity_main.xml中

<LinearLayout 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:orientation="vertical"
    tools:context="com.example.user.sample.MainActivity">


    <TextView
        android:onClick="menuHeader"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:text="☰"
        android:layout_alignParentTop="true"
        android:background="#931d21"
        android:gravity="center_vertical"
        android:paddingLeft="10dp" />


    <fragment
        android:name="com.example.user.sample.MenuFragment"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/fragment_container" />

</LinearLayout

MainActivity.java

package com.example.user.sample;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;

public class MainActivity extends FragmentActivity {

    private MenuFragment fragment;

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

    public void menuHeader(View view) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        fragment = new MenuFragment();
        fragmentTransaction.add(R.id.fragment_container, fragment);
        fragmentTransaction.commit();
    }

}

MenuFragment.java

package com.example.user.sample;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * A fragment representing a list of Items.
 * <p/>
 * Activities containing this fragment MUST implement the {@link OnListFragmentInteractionListener}
 * interface.
 */
public class MenuFragment extends Fragment {

    // TODO: Customize parameter argument names
    private static final String ARG_COLUMN_COUNT = "column-count";
    // TODO: Customize parameters
    private int mColumnCount = 1;
    private OnListFragmentInteractionListener mListener;

    /**
     * Mandatory empty constructor for the fragment manager to instantiate the
     * fragment (e.g. upon screen orientation changes).
     */
    public MenuFragment() {
    }

    // TODO: Customize parameter initialization
    @SuppressWarnings("unused")
    public static MenuFragment newInstance(int columnCount) {
        MenuFragment fragment = new MenuFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_COLUMN_COUNT, columnCount);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_menu_list, container, false);

        // Set the adapter
        if (view instanceof RecyclerView) {
            Context context = view.getContext();
            RecyclerView recyclerView = (RecyclerView) view;
            if (mColumnCount <= 1) {
                recyclerView.setLayoutManager(new LinearLayoutManager(context));
            } else {
                recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
            }
        }
        return view;
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnListFragmentInteractionListener) {
            mListener = (OnListFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnListFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnListFragmentInteractionListener {
        // TODO: Update argument type and name
//        void onListFragmentInteraction(DummyItem item);
    }
}

logcat的

02-10 10:11:19.236 3643-3643/com.example.user.sample E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.sample, PID: 3643
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.user.sample/com.example.user.sample.MainActivity}: android.view.InflateException: Binary XML file line #23: Error inflating class fragment
   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3190)
   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3300)
   at android.app.ActivityThread.access$1000(ActivityThread.java:211)
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1705)
   at android.os.Handler.dispatchMessage(Handler.java:102)
   at android.os.Looper.loop(Looper.java:145)
   at android.app.ActivityThread.main(ActivityThread.java:6946)
   at java.lang.reflect.Method.invoke(Native Method)
   at java.lang.reflect.Method.invoke(Method.java:372)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
Caused by: android.view.InflateException: Binary XML file line #23: Error inflating class fragment
   at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:770)
   at android.view.LayoutInflater.rInflate(LayoutInflater.java:813)
   at android.view.LayoutInflater.inflate(LayoutInflater.java:511)
   at android.view.LayoutInflater.inflate(LayoutInflater.java:415)
   at android.view.LayoutInflater.inflate(LayoutInflater.java:366)
   at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:450)
   at android.app.Activity.setContentView(Activity.java:2366)
   at com.example.user.sample.MainActivity.onCreate(MainActivity.java:16)
   at android.app.Activity.performCreate(Activity.java:6575)
   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1134)
   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3143)
   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3300) 
   at android.app.ActivityThread.access$1000(ActivityThread.java:211) 
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1705) 
   at android.os.Handler.dispatchMessage(Handler.java:102) 
   at android.os.Looper.loop(Looper.java:145) 
   at android.app.ActivityThread.main(ActivityThread.java:6946) 
   at java.lang.reflect.Method.invoke(Native Method) 
   at java.lang.reflect.Method.invoke(Method.java:372) 
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404) 
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199) 
Caused by: java.lang.RuntimeException: com.example.user.sample.MainActivity@197f8eef must implement OnListFragmentInteractionListener
   at com.example.user.sample.MenuFragment.onAttach(MenuFragment.java:75)
   at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1231)
   at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1472)
   at android.support.v4.app.FragmentManagerImpl.addFragment(FragmentManager.java:1691)
   at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:3413)
   at android.support.v4.app.FragmentController.onCreateView(FragmentController.java:120)
   at android.support.v4.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:378)
   at android.support.v4.app.BaseFragmentActivityHoneycomb.onCreateView(BaseFragmentActivityHoneycomb.java:33)
   at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:79)
   at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:740)
   at android.view.LayoutInflater.rInflate(LayoutInflater.java:813) 
   at android.view.LayoutInflater.inflate(LayoutInflater.java:511) 
   at android.view.LayoutInflater.inflate(LayoutInflater.java:415) 
   at android.view.LayoutInflater.inflate(LayoutInflater.java:366) 
   at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:450) 
   at android.app.Activity.setContentView(Activity.java:2366) 
   at com.example.user.sample.MainActivity.onCreate(MainActivity.java:16) 
   at android.app.Activity.performCreate(Activity.java:6575) 
   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1134) 
   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3143) 
   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3300) 
   at android.app.ActivityThread.access$1000(ActivityThread.java:211) 
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1705) 
   at android.os.Handler.dispatchMessage(Handler.java:102) 
   at android.os.Looper.loop(Looper.java:145) 
   at android.app.ActivityThread.main(ActivityThread.java:6946) 
   at java.lang.reflect.Method.invoke(Native Method) 
   at java.lang.reflect.Method.invoke(Method.java:372) 
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404) 
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199) 

片段将显示何时单击☰。但由于活动布局中存在片段,应用程序崩溃了。

我已经有了片段的布局,我没有对它进行任何更改,所以我不知道是否需要在此处发布。感谢

1 个答案:

答案 0 :(得分:1)

你的错误是这个

.RuntimeException:com.example.user.sample.MainActivity@197f8eef必须实现OnListFragmentInteractionListener

因此,您的活动需要实现OnListFragmentInteractionListener。

所以添加

public class MainActivity extends FragmentActivity implements
                                                    OnListFragmentInteractionListener{

....