不兼容的片段类型

时间:2015-10-02 17:14:47

标签: java android android-fragments

我想用导航抽屉制作应用程序。 问题是,一旦我启动模拟器,我会收到警告:

“错误:(63,77)错误:不兼容的类型:FaecherFragment无法转换为Fragment”。

MainActivity中的错误说:

“错误的第二个参数类型。发现:'com.example.android.test6.FaecherFragment',必需'android.support.v4.app.Fragment'”

我已经发现了一些类似的问题,这些问题都可以通过将'import.app.support.v4.app.Fragment'中的import语句更改为'android.app.Fragment'来解决,反之亦然。 .sadly这对我不起作用...我在每一个片段或类中都尝试了这两者的每一个组合,但是它不起作用。

我也尝试更改我的片段,因此它扩展了'android.support.v4.app.Fragment'......这也不起作用。

我是android的新手,所以也许这只是一个初学者的错误......无论如何,我真的希望有人可以帮助我!!

MainActivity:

package com.example.android.test6;

import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;


public class MainActivity extends AppCompatActivity
    implements NavigationDrawerFragment.NavigationDrawerCallbacks,        FaecherFragment.OnFragmentInteractionListener {

/**
 * Fragment managing the behaviors, interactions and presentation of the navigation drawer.
 */
private NavigationDrawerFragment mNavigationDrawerFragment;

/**
 * Used to store the last screen title. For use in {@link #restoreActionBar()}.
 */
private CharSequence mTitle;

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

    mNavigationDrawerFragment = (NavigationDrawerFragment)
            getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
    mTitle = getTitle();

    // Set up the drawer.
    mNavigationDrawerFragment.setUp(
            R.id.navigation_drawer,
            (DrawerLayout) findViewById(R.id.drawer_layout));
}

@Override
public void onNavigationDrawerItemSelected(int position) {
    // update the main content by replacing fragments
    FragmentManager fragmentManager = getSupportFragmentManager();

    switch (position) {
        case 0:
            fragmentManager.beginTransaction()
                    .replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
                    .commit();
            break;
        case 1:
            fragmentManager.beginTransaction()
                    .replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
                    .commit();
            break;
        case 2:
            fragmentManager.beginTransaction()
                    .replace(R.id.container, FaecherFragment.newInstance("a","b"))
                    .commit();
            break;
    }
}

public void onSectionAttached(int number) {
    switch (number) {
        case 1:
            mTitle = getString(R.string.title_section1);
            break;
        case 2:
            mTitle = getString(R.string.title_section2);
            break;
        case 3:
            mTitle = getString(R.string.title_section3);
            break;
    }
}

public void restoreActionBar() {
    ActionBar actionBar = getSupportActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
    actionBar.setDisplayShowTitleEnabled(true);
    actionBar.setTitle(mTitle);
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    if (!mNavigationDrawerFragment.isDrawerOpen()) {
        // Only show items in the action bar relevant to this screen
        // if the drawer is not showing. Otherwise, let the drawer
        // decide what to show in the action bar.
        getMenuInflater().inflate(R.menu.main, menu);
        restoreActionBar();
        return true;
    }
    return super.onCreateOptionsMenu(menu);
}

@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 onFragmentInteraction(String id) {

}

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

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        ((MainActivity) activity).onSectionAttached(
                getArguments().getInt(ARG_SECTION_NUMBER));
    }
}

}

FaecherFragment:

package com.example.android.test6;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.app.ListFragment;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

/**
* A fragment representing a list of Items.
* <p/>
* <p/>
* Activities containing this fragment MUST implement the {@linkOnFragmentInteractionListener}
* interface.
*/
public class FaecherFragment extends ListFragment {

// 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 of parameters
public static FaecherFragment newInstance(String param1, String param2) {
    FaecherFragment fragment = new FaecherFragment();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}

/**
 * Mandatory empty constructor for the fragment manager to instantiate the
 * fragment (e.g. upon screen orientation changes).
 */
public FaecherFragment() {
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }

    // TODO: replace hardcoded Faecher
    List<Faecher> faecherList = new ArrayList<Faecher>();
    faecherList.add(new Faecher("Mathe"));
    faecherList.add(new Faecher("Englisch"));
    faecherList.add(new Faecher("Sport"));
    setListAdapter(new ArrayAdapter<Faecher>(getActivity(),
            android.R.layout.simple_list_item_1, android.R.id.text1, faecherList));
}


@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;
}

@Override
public void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);

    //to start a new activity we have to declare an intent, this intent needs a context (the
    //activity in which we are) and the class that we want to pass the intent into
    Intent intent = new Intent(getActivity(), FaecherDetailsActivity.class);
    //now we take the clicked listitem from our listView l and store it inside a variable
    String title = l.getItemAtPosition(position).toString();
    //we give this variable to the intent (as an extra)
    intent.putExtra("value_title", title);
    //now we start the activity
    getActivity().startActivity(intent);

    if (null != mListener) {
        // Notify the active callbacks interface (the activity, if the
        // fragment is attached to one) that an item has been selected.
        //mListener.onFragmentInteraction(DummyContent.ITEMS.get(position).id);
    }
}

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

}

3 个答案:

答案 0 :(得分:1)

你有

d

将导入更改为支持列表片段

答案 1 :(得分:0)

导入错误的类。您必须从支持库导入片段:

    import android.support.v4.app.ListFragment;

答案 2 :(得分:0)

FaecherFragment延长ListFragmentListFragment扩展Fragment。此Fragmentsupport.v4.app.FragmentManager不兼容。

因此,您可以将FaecherFragment扩展 support.v4.app.ListFragment 扩展为support.v4.app.Fragment