【问题标题】:How to run only one fragment on screen?如何在屏幕上只运行一个片段?
【发布时间】:2014-03-26 05:14:05
【问题描述】:

我想从另一个片段运行单个片段。我试试:

public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.lecturers_fragment,
            container, false);
    ListView list = (ListView) rootView.findViewById(R.id.lecturersList);
    final List<Lecturer> allLecturersList = LecturerDatabaseHelper
            .getAllLecturers(getActivity());
    if (allLecturersList != null) {
        LecturerItemAdapter lecturerAdapter = new LecturerItemAdapter(
                mCurrentActivity, allLecturersList);
        list.setAdapter(lecturerAdapter);
    }
    list.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view,
                int index, long id) {

            Lecturer lecturer = allLecturersList.get(index);
            L.i("Boulder name  is playing link it contains"
                    + lecturer.getName());

            Intent intent_lecturer = new Intent(mCurrentActivity,
                    LecturerFragment.class);
            intent_lecturer.putExtra(LecturerFragment.SELECTED_LECTURER,
                    lecturer);
            mCurrentActivity.startActivity(intent_lecturer);
        }
    });
    return rootView;
}

在我的 logcat 中,我有这个:

03-25 22:04:36.092: E/AndroidRuntime(12453): Caused by: java.lang.ClassCastException: com.asi.sesjaapp.view.LecturerFragment cannot be cast to android.app.Activity

我该怎么做?

【问题讨论】:

  • 我今天已经回答了这个问题:stackoverflow.com/a/22637001/2668136^^
  • 你不能写new Intent(mCurrentActivity, LecturerFragment.class)然后mCurrentActivity.startActivity(intent_lecturer);,因为LecturerFragment类继承自Fragment,而不是Activity
  • Fllo 但我从另一个片段而不是活动中运行它。
  • @Json 我的错,对不起;)

标签: java android android-fragments


【解决方案1】:
  Intent intent_lecturer = new Intent(getActivity(), YourActivity.class);
            intent_lecturer.putExtra(LecturerFragment.SELECTED_LECTURER, lecturer);
            mCurrentActivity.startActivity(intent_lecturer);

你在一个片段中,而不是 mCurrentActivity 只是给你的父活动,像这样:

new Intent(getActivity() , LecturerFragment.class);

看起来 LecturerFragment.class 是一个片段,它应该是一个活动。

注意:确保您的父活动扩展 FragmentActivity

如果此答案对您没有帮助,请发布您的父活动代码和片段代码。

【讨论】:

  • 我尝试使用您的代码。我当我点击什么都没有发生。 FragmentActivity 是父片段还是它调用 LecturerFragment 的片段?
  • 您的父活动应该扩展 Fragmentactivity。确保 LecturerFragment 是一个活动而不是一个片段。你也必须从意图开始活动,即这样做: startActivity(intent_lecturer);而不是你是怎么做的。
  • 但是 LecturerFragment 必须是一个片段。我有理由这样做。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-06
  • 1970-01-01
  • 1970-01-01
  • 2021-03-02
  • 1970-01-01
相关资源
最近更新 更多