ClassCastException:Main Activity必须实现onFragmentInteractonListener

时间:2015-10-16 06:18:09

标签: android android-fragments navigation-drawer

当我尝试为导航抽屉项目实现onClick时,我得到了ClassCastException。

请找到以下代码。

我无法弄清楚它出错的地方

MainActivity:

    #include <iostream>
    #include <fstream>
    #include <sstream>
    #include <string>

    using namespace std;

    int main() {
        bool empt = false;
        int num_ppl = 0;
        int num_spoilt = 0;
        ofstream names2 ("names2.txt");

        if (names2.is_open()) {
            int a = 0;
            while(1) {
            string line;
            getline(cin, line);
            if (line.length() == 0) {
                empt = true;
                break;
            }
            if (((line[a] >= 'A') && (line[a] <= 'Z')) || 
                ((line[a] >= 'a') && (line[a] <= 'z'))) {
                cout << line << endl;
                names2 << line;
                names2 << endl;
                num_ppl++;
            } else {
                break;
            }
            a++;    
        }
        names2.close();
    }
}

ContactFragment:

public class MainActivity extends AppCompatActivity implements FragmentDrawer.FragmentDrawerListener {

Toolbar toolbar;
ViewPager pager;
ViewPagerAdapter adapter;
SlidingTabLayout tabs;
CharSequence Titles[] = {"CITY", "GO", "NEAR"};
int Numboftabs = 3;
private FragmentDrawer drawerFragment;
private Handler mHandler;

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


    // Creating The Toolbar and setting it as the Toolbar for the activity

    toolbar = (Toolbar) findViewById(R.id.app_bar);
    setSupportActionBar(toolbar);


    // Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
    adapter = new ViewPagerAdapter(getSupportFragmentManager(), Titles, Numboftabs);

    // Assigning ViewPager View and setting the adapter
    pager = (ViewPager) findViewById(R.id.pager);
    pager.setAdapter(adapter);

    // Assiging the Sliding Tab Layout View
    tabs = (SlidingTabLayout) findViewById(R.id.tabs);
    tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width

    // Setting Custom Color for the Scroll bar indicator of the Tab View
    tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
        @Override
        public int getIndicatorColor(int position) {
            return getResources().getColor(R.color.tabsScrollColor);
        }
    });

    // Setting the ViewPager For the SlidingTabsLayout
    tabs.setViewPager(pager);


    drawerFragment = (FragmentDrawer)
            getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
    drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), toolbar);
    drawerFragment.setDrawerListener(this);


    // display the first navigation drawer view on app launch
    displayView(0);

}


@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_main, 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);
}

@Override
public void onDrawerItemSelected(View view,  final int position) {
displayView(position);

}
private void displayView(int position) {
    Fragment fragment = null;
    String title = getString(R.string.app_name);
    switch (position) {
        case 0:
            fragment = new ContactFragment();
            title = getString(R.string.nav_item_contact);

            break;
        case 1:
            fragment = new MyLocation();

            title = getString(R.string.nav_item_myloc);
            break;

        case 2:
            fragment = new TermsandCondition();
            title = getString(R.string.nav_item_terms);
            break;

        case 3:
            fragment = new UpgradePlan();
            title = getString(R.string.nav_item_upgrade);
            break;
        case 4:
            fragment = new Aboutus();
            title = getString(R.string.nav_item_about);


            break;


        default:
            break;
    }
    if (fragment != null) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        //   fragmentTransaction.setCustomAnimations(android.R.anim.fade_in,android.R.anim.fade_out,android.R.anim.fade_in,android.R.anim.fade_out);
        fragmentManager.addOnBackStackChangedListener(null);
        fragmentTransaction.replace(R.id.container_body, fragment);
        fragmentTransaction.commit();

        // set the toolbar title
        // actionBar.setTitle(Html.fromHtml("<font color='#ff0000'>ActionBartitle </font>"));
        getSupportActionBar().setTitle(Html.fromHtml("<font color='#000000'>" + title + " </font>"));
        //  final Drawable upArrow = getResources().getDrawable(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
        //  upArrow.setColorFilter(getResources().getColor(R.color.grey), PorterDuff.Mode.SRC_ATOP);
        // getSupportActionBar().setHomeAsUpIndicator(upArrow);


    }
}
}

logcat的:

public class ContactFragment 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;


// TODO: Rename and change types and number of parameters
public static ContactFragment newInstance(String param1, String param2) {
    ContactFragment fragment = new ContactFragment();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}

public ContactFragment() {
    // 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_contact, 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;
}

public interface OnFragmentInteractionListener {
    // TODO: Update argument type and name
    public void onFragmentInteraction(Uri uri);
}

}

任何帮助表示赞赏!!

2 个答案:

答案 0 :(得分:4)

<强>解决方案

将此添加到您的MainActivity

public class MainActivity extends AppCompatActivity implements FragmentDrawer.FragmentDrawerListener,ContactFragment.OnFragmentInteractionListener {

并覆盖public void onFragmentInteraction(Uri uri)

MainActivity中的方法

发生此错误是因为您未在托管interface的{​​{1}}中实施Activity。您需要实施所有Fragments的{​​{1}}。

<强>解释

您可以在interface编写条件的Fragments中看到此信息,以查看托管活动是否已实施基础onAttach()。< / p>

理想的建议是,如果您不打算使用Fragment和其他内容,请从Fragment Interface中移除interface,否则请继续执行接口。

您可以询问是否需要进一步解释。

并且是的,我建议您阅读以下内容以更广泛地了解fragment内容, Fragment Basics

答案 1 :(得分:0)

您正在使用片段中的接口将片段中的值(可能是您单击的片段中的视图)从片段传递到活动。

如果您不需要将任何此类值从片段传递到活动,则可以删除它们,否则您可以将片段中的值传递给其界面中的方法,并且可以将活动中的方法覆盖为访问该参数。因为您不需要将任何内容从片段传递到活动,所以您可以从片段中删除该界面。所有碎片的情况都是一样的。