我本质上是一名新的Android Studio开发人员,目前我正在尝试在我的程序的3个标签之间切换。不幸的是,当我试图打开时,程序会结束。我不完全确定问题出在哪里,因为我在选项卡中声明了一个类的实例。
MainActivity.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);
}
}
我已经在其他网站上寻求过帮助,主要是它们涵盖过时的程序或者完全没有涵盖这个问题,我没有其他任何内容可以解决这个问题的任何帮助我&# 39;欣赏它。
编辑:我已经知道它与创建一个类的.newinstance有关,但是如何实现它我还没有完全掌握。
Logcat输出。仅包含错误部分
10-29 21:04:04.599 9452-9452 / com.example.main E / AndroidRuntime:致命异常:主要 过程:com.authpayx.authportbeta04,PID:9452 java.lang.ClassCastException:com.example.main.main@42d45398必须实现 OnFragmentInteractionListener at com.example.main.Tab1.onAttach(Tab1.java:84) 在android.app.FragmentManagerImpl.moveToState(FragmentManager.java:849) 在android.app.FragmentManagerImpl.performPendingDeferredStart(FragmentManager.java:785) 在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.ViewPager.populate(ViewPager.java:919) 在android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1441) 在android.view.View.measure(View.java:17478) 在android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5364) 在android.widget.FrameLayout.onMeasure(FrameLayout.java:310) 在android.view.View.measure(View.java:17478) 在android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5364) 在com.android.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:412) 在android.view.View.measure(View.java:17478) 在android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5364) 在android.widget.FrameLayout.onMeasure(FrameLayout.java:310) 在com.android.internal.policy.impl.PhoneWindow $ DecorView.onMeasure(PhoneWindow.java:2548) 在android.view.View.measure(View.java:17478) 在android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2262) 在android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1391) 在android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1590) 在android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1249) 在android.view.ViewRootImpl $ TraversalRunnable.run(ViewRootImpl.java:6585) 在android.view.Choreographer $ CallbackRecord.run(Choreographer.java:803) 在android.view.Choreographer.doCallbacks(Choreographer.java:603) 在android.view.Choreographer.doFrame(Choreographer.java:573) 在android.view.Choreographer $ FrameDisplayEventReceiver.run(Choreographer.java:789) 在android.os.Handler.handleCallback(Handler.java:733) 在android.os.Handler.dispatchMessage(Handler.java:95) 在android.os.Looper.loop(Looper.java:136) 在android.app.ActivityThread.main(ActivityThread.java:5579) at java.lang.reflect.Method.invokeNative(Native Method) 在java.lang.reflect.Method.invoke(Method.java:515) 在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:1268) 在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084) 在dalvik.system.NativeStart.main(本地方法)
答案 0 :(得分: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重新创建您的片段时,它的数据包会粘在一起。
您不关心新实例的唯一时间是您没有将任何内容传递到您的片段中。
答案 1 :(得分: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片段类,请不要使用Fragment Class中的注释。
/**
* 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);
}
答案 2 :(得分: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");
}
}
这些代码,问题解决了