我有一个带按钮的Activity1。
单击此按钮时,我想调用Activity2:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:orientation="vertical"
android:id="@+id/frag_container"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout >在这个"frag_container“中,我想添加一个Fragment1:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:src="@drawable/ic_launcher"
android:scaleType="fitCenter"
android:layout_height="250px"
android:layout_width="250px"/>
<TextView
android:text="Frame Demo"
android:textSize="30px"
android:textStyle="bold"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:gravity="center"/>
</FrameLayout>我可以这样成功地启动Activity2:
Intent intent = new Intent(Activity1.this, Activity2.class);
startActivity(intent);但我不知道如何在Fragment1上启动这个Activity2。
我尝试在Activity2的OnCreate中添加以下内容:
Fragment myFrag = new Fragment1 ();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(R.id.frag_container, myFrag);
ft.commit();但当我调用此活动时,总是会崩溃。
我是Android新手,有人能告诉我怎么做吗?
发布于 2015-09-02 08:14:54
您是否在片段中看到了一个名为OnFragmentInteractionListener的接口。这是这个问题的根本原因。这没有什么问题,但最好是让您了解那里发生了什么。
在片段中,您还应该重写onAttach方法
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.activity = activity;
}我们也会做一些类似如下的事情,
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.activity = activity;
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (OnHeadlineSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}以确保接口被实现(我认为您的代码中有上面类似的代码)。如果与片段中的活动没有通信,则注释掉onAttach方法。
在这种情况下,您必须在Activity2上实现OnFragmentInteractionListener。那么它应该是有效的。我们对片段使用此接口来与活动进行通信。这就是我们怎么做的。
如果您通过覆盖片段中的onAttach来附加activity,这意味着您必须实现接口(但这并不重要,除非您调用这些接口方法从片段中回调Activity )
请查看this以了解有关片段和活动之间通信的更多信息。
发布于 2015-09-02 01:43:26
使用Get activity获取父活动,然后照常执行。
Intent intent = new Intent(getActivity(), Activity2.class);
getActivity().startActivity(intent); https://stackoverflow.com/questions/32336628
复制相似问题