【问题标题】:Trying to show Google Maps inside fragment dynamically, error inflating class fragment试图在片段内动态显示谷歌地图,错误膨胀类片段
【发布时间】:2016-10-23 07:46:16
【问题描述】:

我是 Android 新手,所以这可能是我犯的一个非常明显的错误。

我正在尝试让我的片段显示 Google 地图,但它不断使应用程序崩溃。错误信息是

“java.lang.RuntimeException:无法启动活动 ComponentInfo{com.example.daniel.mts/com.example.daniel.mts.MainActivity}:android.view.InflateException:二进制 XML 文件第 12 行:膨胀错误类片段”

这是我的 MainActivity,它显示了一个工具栏,并将 activity_main.xml 中的 FrameLayout 替换为我的 HomeFragment。

public class MainActivity extends AppCompatActivity
implements OnFragmentInteractionListener {

private DrawerLayout mDrawer;
private Toolbar toolbar;
private NavigationView nvDrawer;
private ActionBarDrawerToggle drawerToggle;

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

    //Set toolbar to replace the action bar
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    //find drawer view
    mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawerToggle = setupDrawerToggle();

    //Tie drawerlayout events to the action bar toggle for open and        close
    mDrawer.addDrawerListener(drawerToggle);

    //Find our drawer view
    nvDrawer = (NavigationView) findViewById(R.id.nvView);

    //Setup drawer view
    setUpDrawerContent(nvDrawer);

    Fragment fragment = null;
    Class fragmentClass = HomeFragment.class;
    try {
        fragment = (Fragment) fragmentClass.newInstance();
    } catch (Exception e) {
        e.printStackTrace();
    }
    FragmentTransaction def =   getSupportFragmentManager().beginTransaction();
    def.replace(R.id.flContent, fragment);
    def.commit();
}

这是我的活动主 xml 文件

<!-- This LinearLayout represents the contents of the screen  -->
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <!-- The toolbar displayed at the top -->
    <include
        layout="@layout/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <!-- The main content view where fragments are loaded -->
    <FrameLayout
        android:id="@+id/flContent"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

<!-- The navigation drawer that comes from the left -->
<!-- android:layout_gravity needs to be set to 'start' -->
<android.support.design.widget.NavigationView
    android:id="@+id/nvView"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:background="@android:color/white"
    app:menu="@menu/drawer_view"
    app:headerLayout="@layout/nav_header" />

</android.support.v4.widget.DrawerLayout>

我的 HomeFragment 仅包含创建新片段的样板代码,它显示我的 home_fragment.xml

public class HomeFragment extends Fragment {

// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";

// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;

private OnFragmentInteractionListener mListener;

public HomeFragment() {
    // Required empty public constructor
}

/**
 * Use this factory method to create a new instance of
 * this fragment using the provided parameters.
 *
 * @param param1 Parameter 1.
 * @param param2 Parameter 2.
 * @return A new instance of fragment HomeFragment.
 */
// TODO: Rename and change types and number of parameters
public static HomeFragment newInstance(String param1, String param2)   {
    HomeFragment fragment = new HomeFragment();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup   container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.home_fragment, container,   false); }


// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
    if (mListener != null) {
        mListener.onFragmentMessage("hello", uri);
    }
}

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

@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.htm l"
 * >Communicating with Other Fragments</a> for more information.
 */
public void onFragmentMessage(String MSG, Object data) {

}

这是我的 home_fragment.xml,它显示应该显示地图的片段。

<FrameLayout
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"
tools:context="com.example.daniel.mts.HomeFragment">

<TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="@string/home_frag" />

<fragment
    android:id="@+id/map"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    class="com.google.android.gms.maps.SupportMapFragment" />
</FrameLayout>

这是我的清单文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.daniel.mts">

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission   android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_bus"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".MainActivity"
        android:screenOrientation="portrait"
        >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER"   />
        </intent-filter>
    </activity>

    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />

    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="@string/google_api_key"/>
</application>



</manifest>

我在哪里搞砸了?

【问题讨论】:

  • 干得好,只需添加错误消息。 “描述问题。'它不起作用'不是问题陈述。告诉我们预期的行为应该是什么。告诉我们错误消息的确切措辞是什么,以及产生它的代码行。放一个您的问题标题中的问题的简要摘要。”来自How to create a Minimal, Complete, and Verifiable example
  • @MikeJRamsey56 已更新,谢谢

标签: android google-maps android-fragments


【解决方案1】:

基于Fragments,您可以使用以下两种方式之一将片段添加到活动布局:

  • 在 Activity 的布局文件中声明片段。

在这种情况下,您可以为片段指定布局属性,就像它是一个视图一样。

当系统创建此活动布局时,它会实例化布局中指定的每个片段,并为每个片段调用onCreateView() 方法,以检索每个片段的布局。系统将fragment返回的View直接插入到&lt;fragment&gt;元素的位置。

  • 或者,以编程方式将片段添加到现有的ViewGroup

要在您的活动中进行片段事务(例如添加、删除或替换片段),您必须使用来自FragmentTransaction 的 API。您可以像这样从您的活动中获取FragmentTransaction 的实例:

FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

然后您可以使用add() 方法添加片段,指定要添加的片段以及插入片段的视图。例如:

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

您可以查看给定的文档以获取完整的详细信息。

除此之外,您还可以尝试@Edoardo Moreni 在此SO post 中使用的解决方案,其中他能够通过从 xml 中删除片段,将其插入到活动 xml 中并通过onCreateView (from the fragment class) 给超类。

希望有帮助!

【讨论】:

    猜你喜欢
    • 2012-12-14
    • 1970-01-01
    • 1970-01-01
    • 2013-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-26
    • 1970-01-01
    相关资源
    最近更新 更多