【发布时间】:2014-07-23 18:45:42
【问题描述】:
我问了一个关于如何添加包含使用 OpenGL ES 绘制的内容的 Fragment 的问题
here。有人很好地为我回答了这个问题,但不幸的是今天我遇到了另一个问题。正如我在另一个问题中提到的那样,我的目的是在包含 OpenGL 的那个旁边添加其他 Fragments,因为我是 Android 开发的初学者,我似乎不明白这是如何完成的。
这就是我想要的:现在,我的代码正是我的另一个问题中的代码。我也有这个Fragment:
public class TextFragment extends Fragment
{
private TextView textview;
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.text_fragment,
container, false);
textview = (TextView) view.findViewById(R.id.textView1);
return view;
}
}
连同它的布局:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/frag2">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Fragment Two"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
我想将此添加到我的主要活动中,现在我只有 OpenGL Fragment。这是我的主要活动:
public class FragmentExampleActivity extends FragmentActivity implements ToolbarFragment.ToolbarListener
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener()
{
public void onBackStackChanged()
{
int backCount = getSupportFragmentManager().getBackStackEntryCount();
if (backCount == 0)
{
finish();
}
}
});
if (savedInstanceState == null)
{
getSupportFragmentManager()
.beginTransaction()
.add(R.id.main_container, new OpenGLES20ActivityFrag())
.addToBackStack(null)
.commit();
}
}
}
还有 Fragment 里面有 OpenGL 并且我已经添加到主要活动中:
public class OpenGLES20ActivityFrag extends Fragment
{
private GLSurfaceView mGLView;
public OpenGLES20ActivityFrag()
{
super();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
mGLView = new MyGLSurfaceView(this.getActivity());
return mGLView;
}
}
我尝试过但失败了:在getSupportFragmentManager() 中使用另一个对.add 方法的调用,或者为我的第二个Fragment 调整这段代码
getSupportFragmentManager()
.beginTransaction()
.add(R.id.frag2, TextFragment)
.addToBackStack(null)
.commit();
这给了我add 方法中的“预期表达式”错误。我尝试将此构造函数添加到我的第二个Fragment
public TextFragment()
{
super();
}
然后在add 方法里面我放了.add(R.id.frag2, new TextFragment())
还是不行。
【问题讨论】:
-
你应该看到一个教程来学习如何将两个片段放在一起,比如这个:javacodegeeks.com/2013/06/…
-
private static TextView textview;不要将 TextView 设为静态。 -
添加到@Zhuinden 这将造成上下文泄漏。静态可变变量在 Java 中也是不好的做法
-
好的我删除了TextView的静态声明,我会尝试@Zhuinden提供的解决方案并提供反馈
标签: android android-fragments android-fragmentactivity