Android Studio:创建读取片段的滑动选项卡应用程序。强迫关闭

问题描述 投票:1回答:3

我本质上是一个新的Android Studio开发人员,目前我正在尝试在我的程序的3个选项卡之间切换。不幸的是,当我试图打开时,程序会结束。我不完全确定问题在哪里,因为我声明了关于选项卡的类的实例。

main activity.Java

import java.util.Locale;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.support.v13.app.FragmentPagerAdapter;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;


public class Main extends Activity implements ActionBar.TabListener {


    Fragment FragmentTab1 = new Tab1();
    Fragment FragmentTab2 = new Tab2();
    Fragment FragmentTab3 = new Tab3();
    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a
     * {@link FragmentPagerAdapter} derivative, which will keep every
     * loaded fragment in memory. If this becomes too memory intensive, it
     * may be best to switch to a
     * {@link android.support.v13.app.FragmentStatePagerAdapter}.
     */
    SectionsPagerAdapter mSectionsPagerAdapter;

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    ViewPager mViewPager;

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

        // Set up the action bar.
        final ActionBar actionBar = getActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mSectionsPagerAdapter);


        // When swiping between different sections, select the corresponding
        // tab. We can also use ActionBar.Tab#select() to do this if we have
        // a reference to the Tab.
        mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                actionBar.setSelectedNavigationItem(position);
            }
        });

        // For each of the sections in the app, add a tab to the action bar.
        for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
            // Create a tab with text corresponding to the page title defined by
            // the adapter. Also specify this Activity object, which implements
            // the TabListener interface, as the callback (listener) for when
            // this tab is selected.
            actionBar.addTab(
                    actionBar.newTab()
                            .setText(mSectionsPagerAdapter.getPageTitle(i))
                            .setTabListener(this));
        }
    }


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


    @Override
    public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
        // When the given tab is selected, switch to the corresponding page in
        // the ViewPager.
        mViewPager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    }

    @Override
    public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a PlaceholderFragment (defined as a static inner class below).
            Fragment fragment = null;
            if (position == 0)
            {
                fragment = FragmentTab1;
            }
            if (position == 1)
            {
                fragment = FragmentTab2;
            }
            if (position == 2)
            {
                fragment = FragmentTab3;
            }
            return fragment;
        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 3;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            Locale l = Locale.getDefault();
            switch (position) {
                case 0:
                    return getString(R.string.title_section1).toUpperCase(l);
                case 1:
                    return getString(R.string.title_section2).toUpperCase(l);
                case 2:
                    return getString(R.string.title_section3).toUpperCase(l);
            }
            return null;
        }
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            return rootView;
        }
    }

Tab1(其他2个标签相同)

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 Tab1.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link Charge#newInstance} factory method to
 * create an instance of this fragment.
 *
 */
public class Tab1 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 Tab1
     */
    // TODO: Rename and change types and number of parameters
    public static Charge newInstance(String param1, String param2) {
        Tab1 fragment = new Tab1();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }
    public Tab1() {
        // 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_tab1, 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);
    }

}

我已经在其他网站上寻求帮助,主要是它们涵盖了过时的程序或者没有完全涵盖这个问题,我没有其他任何内容可以转向,所以对这个问题有任何帮助我会很感激。

编辑:我已经知道它与创建类的.newinstance有关,但是如何实现它我还没有完全掌握。

Logcat输出。仅包含错误部分

10-29 21:04:04.599 9452-9452 / com.example.main E / AndroidRuntime:FATAL EXCEPTION:main进程:com.authpayx.authportbeta04,PID:9452 java.lang.ClassCastException:com.example.main.main @ 42d45398必须在android.app.FragmentManagerImpl.performPendingDeferredStart(FragmentManager.java:785)的android.app.FragmentManagerImpl.moveToState(FragmentManager.java:849)的com.example.main.Tab1.onAttach(Tab1.java:84)处实现OnFragmentInteractionListener。 )android.sapp.FranmentCompat中的android.app.Fragment.setUserVisibleHint(Fragment.java:997)android.support.v13.app.FragmentCompatICSMR1.setUserVisibleHint(FragmentCompatICSMR1.java:23)android.support.v13.app.FragmentCompat $ ICSMR1FragmentCompatImpl.setUserVisibleHint( FragmentCompat.java:48)在android.support.v13.app.FragmentCompat.setUserVisibleHint(FragmentCompat.java:76)的android.support.v13.app.FragmentPagerAdapter.setPrimaryItem(FragmentPagerAdapter.java:134)android.support.v4 .view.ViewPager.populate(ViewPager.java:1071)在android.support.v4.view.ViewPa ger.populate(ViewPager.java:919)位于android.view.View的View.jat.View(1.4),安装在android.view.View.View(View.java:17478)的android.view. .measureChildWithMargins(ViewGroup.java:5364)位于android.view.measure.View.measure(View.java:17478)的android.widget.FrameLayout.onMeasure(FrameLayout.java:310),位于android.view.ViewGroup.measureChildWithMargins(ViewGroup。 java:5364)com.android.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:412)at android.view.vision.measure(View.java:17478)at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java) :5364)在android.view.View.measure的com.android.internal.policy.impl.PhoneWindow $ DecorView.onMeasure(PhoneWindow.java:2548)的android.widget.FrameLayout.onMeasure(FrameLayout.java:310) View.java:17478)在android.view.ViewRootImpl.performMevers(ViewRootImpl.java:2262)的android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1391)android.view.ViewRootImpl.performTraversals(ViewR) ootImpl.java:1590)在android.view.ViewRootImpl上的android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1249)$ traversalRunnable.run(ViewRootImpl.java:6585)在android.view.Choreographer $ CallbackRecord.run(编舞) .java:803)在android.view.Chopographer.doCrame(Choreographer.java:603)的android.view.Choreographer,我发现在android.view.Choreographer(Choreographer.java:573)的android.view.Choreographer $ FrameDisplayEventReceiver.run(Choreographer.java: 789)在android.os.Handler.dhandatchMessage(Handler.java:95)的android.os.Handler.handleCallback(Handler.java:95)android.os.Looper.loop(Looper.java:136)。 app.ActivityThread.main(ActivityThread.java:5579)位于com.android.internal的java.lang.reflect.Method.invoke(Method.java:515)的java.lang.reflect.Method.invokeNative(Native Method)中。 os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:1268)at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)at dalvik.system.NativeStart.main(Native Method)

java android android-fragments tabs swipeview
3个回答
0
投票

您必须在主活动中实现OnFragmentInteractionListener。更改

public class Main extends Activity implements ActionBar.TabListener

public class Main extends Activity implements ActionBar.TabListener, OnFragmentInteractionListener

然后确保你的工具

public void onFragmentInteraction(Uri uri);

在你的主要活动中。

关于新实例方法的一点信息。这是一种常见的做法,而不是您正在实施的特殊方法。你可以把它叫做任何你想要的东西,但想法是新的实例方法获取你的参数并将它们添加到一个包中。当android破坏你的片段时,它会使用它没有你的数据的默认构造函数重新创建。

解决方案是使用一个新的实例方法并将您的数据放入一个包中,因为当android重新创建您的片段时,它的数据包会粘在一起。

您不关心新实例的唯一时间是您没有将任何内容传递到您的片段中。


0
投票

看来这个问题与你的Tab1 Fragment类有关。另外你似乎是通过android studio自动生成的Fragment类创建了这个Fragment类。 要解决此问题,您可以使用下面的代码更改自动生成的片段类代码,如Tab1。

package com.example.android.actionbarcompat.styled;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
* Created by taher on 1/7/15.
*/
public class MainFragment extends Fragment {
 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.main_view, container, false);
 }
}

如果你想使用你的Tab1片段类,请不要在你的片段类下面评论。

/**
 * 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);
}

0
投票

我有同样的问题,在我的情况下,删除

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        mListener = (OnFragmentInteractionListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement OnFragmentInteractionListener");
    }
}

这些代码,问题解决了

© www.soinside.com 2019 - 2024. All rights reserved.