应用程序崩溃:Android 使用片段

App Crash : Android using Fragments

我正在使用 android studio 和片段编写应用程序。 当我尝试动态加载片段时应用程序崩溃。

我正在添加下面的代码。

fragment_setup.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.pchakraverti.streetsecure.setup_fragment"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:gravity="center"
    android:layout_gravity="center"
    android:clickable="false"
    android:focusableInTouchMode="false">

    <!-- TODO: Update blank fragment layout -->

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">

    </LinearLayout>

    <LinearLayout
        android:visibility="invisible"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:id="@+id/prgLayout">

    </LinearLayout>

    <ProgressBar
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/progressBar"
        android:indeterminate="true"
        android:indeterminateOnly="true"
        android:layout_gravity="left|bottom"
        android:layout_marginBottom="25sp" />

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="right"
        android:layout_gravity="center_horizontal|bottom"
        android:layoutMode="opticalBounds"
        android:layout_marginBottom="60sp">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Sign Up"
            android:id="@+id/btnSignUp" />

        <Space
            android:layout_width="20px"
            android:layout_height="20px" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Later"
            android:id="@+id/btnLater" />
    </LinearLayout>

    <LinearLayout
        android:orientation="vertical"
        android:paddingTop="15sp"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:layout_gravity="center">

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

        <Space
            android:layout_width="20dp"
            android:layout_height="20dp" />

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textPostalAddress"
            android:ems="10"
            android:id="@+id/editText2"
            android:hint="Address"
            android:layout_gravity="center_horizontal" />

        <Space
            android:layout_width="20dp"
            android:layout_height="20dp" />

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="phone"
            android:ems="10"
            android:id="@+id/editText3"
            android:hint="Phone No." />

        <Space
            android:layout_width="20dp"
            android:layout_height="20dp" />

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textEmailAddress"
            android:ems="10"
            android:id="@+id/editText4"
            android:hint="Email" />
    </LinearLayout>

    <TextView
        android:layout_width="350dp"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Fill in the form below."
        android:id="@+id/lblHeader"
        android:singleLine="true"
        android:textStyle="bold"
        android:typeface="serif"
        android:gravity="center"
        android:layout_gravity="right|top"
        android:layout_marginTop="100sp" />

</FrameLayout>

setup_fragment.java

package com.example.pchakraverti.streetsecure;

import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link setup_fragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link setup_fragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class setup_fragment 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;

    /**
     * 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 setup_fragment.
     */
    // TODO: Rename and change types and number of parameters
    public static setup_fragment newInstance(String param1, String param2) {
        setup_fragment fragment = new setup_fragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

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

    @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.fragment_setup_fragment, container, false);
    }

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

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.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.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        public void onFragmentInteraction(Uri uri);
    }

}

activity_start.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:id="@+id/frag_container"
    tools:context=".StartActivity">

</LinearLayout>

StartActivity.java

package com.example.pchakraverti.streetsecure;

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


public class StartActivity extends FragmentActivity {

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

        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        setup_fragment frag = new setup_fragment();
        fragmentTransaction.add(R.id.frag_container, frag);
        fragmentTransaction.commit();
    }


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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

setup_fragment 包含我要在应用程序启动时加载的 UI。 但是,应用程序在启动时崩溃。

我使用本教程来加载片段: Dynamically add Fragments to an Activity in Android

我们将不胜感激。

编辑

至于logcat,我在logcat上没有看到任何东西(我不知道为什么)。

如果您正在使用支持库(片段 v4),您需要将 setup_fragment 扩展为 android.support。v4.app.fragment 而不是 android.app.Fragment;

你像这样实例化你的片段:

new setup_fragment()

改为使用您定义的工厂方法:

setup_fragment frag = setup_fragment.newInstance(string1, string2);

你的Fragment还需要Activity实现OnFragmentInteractionListener接口,所以你需要在Activity中实现onFragmentInteraction方法,并且声明你的 Activity 如下:

StartActivity extends FragmentActivity implements OnFragmentInteractionListener 

如果正如我所怀疑的那样,您只是使用了 IDE 生成的代码但不打算使用所有代码,您也可以简单地删除不需要的部分、工厂方法和Activity 的界面只是为了您的方便而不是正式要求。

最后,正如 Neige 所指出的,您混淆了 android.app.Fragmentandroid.support.v4.app.Fragment。修复你的进口。如果您希望应用程序使用支持库来支持旧的 OS 版本,请确保导入了正确的 classes(FragmentManagerFragmentTransaction、...支持库中对应class)。

附带说明一下,如果您使用 Java 中最常用的命名约定,即 camelCase.

,许多开发人员可能会很感激