【发布时间】:2012-02-10 14:28:40
【问题描述】:
我正在尝试使我的应用更适合平板电脑,因此我正在尝试学习片段。我想要典型的两窗格布局,左侧是“导航”,单击其中一个元素,它会更改右侧的片段。
我可以复制左侧使用 ListFragment 的教程,如果您单击其中一个,它会更新右侧的“详细信息”片段。
我已尽我所能复制该代码,并仅使用 LinearLayout,左侧带有按钮,因此如果单击按钮,它会在右侧加载适当的片段,但它不起作用.
当我提交 FragmentTransaction 时,我得到 java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first. 孩子的父母是什么,为什么我必须对其调用 removeView?
我正在尝试将片段加载到 FrameLayout 中,但我也刚刚尝试替换布局中的另一个片段,但仍然出现错误。
理想情况下,我希望左侧片段占据整个屏幕,直到按下需要片段从左侧进入的按钮,但我想一次有一个问题。
代码
主要活动
public class FragmentExample2Activity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
SelectorFragment(左侧)
public class SelectorFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View fragment = inflater.inflate(R.layout.selector, container);
Button button1 = (Button) fragment.findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
getFragmentManager().beginTransaction().replace(R.id.detail_holder, new DetailsFragment(), "stuff").commit();
}
});
return fragment;
}
}
DetailsFragment
public class DetailsFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
return inflater.inflate(R.layout.details, container);
}
}
main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<fragment class="com.coreno.testfragment.SelectorFragment"
android:id="@+id/select"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
/>
<fragment class="com.coreno.testfragment.DetailsFragment"
android:id="@+id/detail_holder"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="2"
/>
<!--
<FrameLayout
android:id="@+id/detail_holder"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="2"
/>
-->
</LinearLayout>
【问题讨论】:
标签: java android android-fragments