我正在使用3窗格视图布局(经典的“主要细节”流程)开发应用程序,遵循由mobile tuts创建的2窗格示例。
3窗格布局如下所示:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="0dp"
android:layout_marginRight="0dp"
android:background="?android:attr/detailsElementBackground"
android:divider="?android:attr/dividerHorizontal"
android:orientation="horizontal"
android:showDividers="middle"
tools:context=".SListA" >
<!--
This layout is a three-pane layout for the
master/detail flow.
-->
<fragment
android:id="@+id/s_list"
android:name="com.xxxxx.xxxxxx.SListF"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />
<FrameLayout
android:id="@+id/s_events"
android:paddingLeft="4dp"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />
<FrameLayout
android:id="@+id/s_details"
android:paddingLeft="4dp"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.5" />
尝试在上面的3窗格视图中替换第三个片段面板时遇到问题(在宽/横向平板电脑模式下)。错误位于下面的代码的最后一行,从中间面板片段代码执行:
@Override
public void setEventKey(String event_key) {
if (SListA.m3Pane) {
// In three-pane mode, show the details view in this activity by
// adding or replacing the details fragment using a
// fragment transaction.
Bundle arguments = new Bundle();
arguments.putString(SDetailsF.ARG_EVENTKEY, event_key);
SDetailsF fragment = new SDetailsF();
fragment.setArguments(arguments);
getFragmentManager().beginTransaction()
.replace(R.id.s_details, fragment).commit();
}
上面的最后一行代码显示了编译错误:
无法对非静态方法进行静态引用 来自Fragment
类型的getFragmentManager()
(注意,我已经设置了minSdkVersion = 11) 使用相同的代码替换第二个(中间)面板的片段,我不明白为什么它不适用于第三个面板。唯一的区别是,第二(中间)面板的替换片段代码是从(第一个面板)活动代码中运行的,而不是(第二个面板)片段代码。
我能够使用以下代码替换上述问题代码,而不会出现编译错误:
fragment.getFragmentManager().beginTransaction()
.replace(R.id.s_details, fragment).commit();
但是,在运行期间使用InvocationTargetException消息执行此代码时会崩溃:
“找不到来源”
如何解决此问题的任何想法都将受到高度赞赏。
答案 0 :(得分:2)
您必须使用接口。无论何时需要在片段之间进行通信,都必须在每个片段中声明一个接口,并且该接口必须由持有它的活动实现。然后在片段中的某个事件上,调用活动实现的方法。然后在那个方法中你继续进行必要的动作(在你的情况下改变/替换片段),这必须反映在其他片段中。
检查我的这个答案。它与你必须遵循的类似。