我看过其他的帖子,它们都表明宿主活动java文件没有扩展android.support.v4.app.fragment。但是,我不知道如何使宿主java文件扩展android.support.v4.app.fragment。
我试过将依赖项添加到gradle文件中,但这也不起作用。
以下是宿主活动片段:

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import course.examples.fragmentstaticlayout.TitlesFragment.ListSelectionListener;

public class QuoteViewerActivity extends Activity implements ListSelectionListener{

    public static String[] mTitleArray;
    public static String[] mQuoteArray;
    private QuotesFragment mDetailsFragment;

    private static final String TAG = "QuoteViewerActivity";

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

        mTitleArray = getResources().getStringArray(R.array.Titles);
        mQuoteArray = getResources().getStringArray(R.array.Quotes);

        setContentView(R.layout.main);

        mDetailsFragment = (QuotesFragment) getFragmentManager().findFragmentById(R.id.details);
    }

所讨论的行是代码片段的最后一行。这是我的引用片段。
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class QuotesFragment extends Fragment {

    private TextView mQuoteView = null;
    private int mCurrIdx = -1;
    private int mQuoteArrayLen;

    private static final String TAG = "QuotesFragment";

    public int getShownIndex() {
        return mCurrIdx;
    }

    public void showQuoteAtIndex(int newIndex) {
        if (newIndex < 0 || newIndex >= mQuoteArrayLen)
            return;
        mCurrIdx = newIndex;
        mQuoteView.setText(QuoteViewerActivity.mQuoteArray[mCurrIdx]);
    }

    @Override
    public void onAttach(Context context){
        Log.i(TAG, getClass().getSimpleName() + ":entered onAttach()");

        super.onAttach(context);

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        Log.i(TAG, getClass().getSimpleName() + ":entered onCreate()");
        super.onCreate(savedInstanceState);
    }

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

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mQuoteView = (TextView) getActivity().findViewById(R.id.quoteView);
        mQuoteArrayLen = QuoteViewerActivity.mQuoteArray.length;

    }

假设我对主机活动没有扩展support.v4是正确的,我该如何做?

最佳答案

这是因为您试图将Fragment转换为SupportFragment
您的QuotesFragment正在扩展SupportFragment,并且在投射时您尝试使用返回片段的FragmentManager and fragment,而不是supportFragment
尝试使用geSupportFragmentManager代替getFragmentManager
此外,您还应该扩展appcompatactivity或fragmentactivity,而不是扩展activity以获得引用。
Here is similar question

10-06 12:41