当前位置: 首页 > 知识库问答 >
问题:

无法强制转换Android.app.Fragment

左丘嘉言
2023-03-14

下面是托管活动片段:

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的看法是正确的,那么我该怎么做呢?

共有1个答案

贾骏
2023-03-14

这是因为您正在尝试将fragment强制转换为supportfragment

您的QuotesFragment正在扩展SupportFragment,在强制转换时,您尝试使用FragmentManager和Fragment返回Fragment,而不是SupportFragment

尝试使用gesupportfragmentmanager代替getfragmentmanager

此外,您还应该为QuoteViewerActivity扩展AppCompatActivity或FragmentActivity而不是Activity

这里有类似的问题

 类似资料: