【发布时间】:2013-05-25 22:25:10
【问题描述】:
我有一个带有布局的片段 (fragment_layout.xml)。在此布局中,我想动态更改其一部分(空布局)以插入其他部分布局(第一、第二和第三布局),如图所示。
我不想更改片段的所有布局,只更改其中的一部分。
最好的方法是什么?
【问题讨论】:
我有一个带有布局的片段 (fragment_layout.xml)。在此布局中,我想动态更改其一部分(空布局)以插入其他部分布局(第一、第二和第三布局),如图所示。
我不想更改片段的所有布局,只更改其中的一部分。
最好的方法是什么?
【问题讨论】:
最好的方法是使用 Fragment Transaction。检查此代码,
在您的 Main Activity 中,应该扩展到 FragmentActivity
@Override
public void onClick(View button) {
FragmentTransaction ft=getActivity().getSupportFragmentManager().beginTransaction();
if(button==groups)// If clicked button is groups, set the layout fragment1.xml
{
Fragment fragment = new GroupsFragment();
FragmentManager fm = getActivity().getSupportFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
transaction.replace(R.id.fragment1, fragment);
transaction.commit();
}
else if(button==photos)
{
Fragment fragment2 = new PhotosFragment();
FragmentManager fm2 = getActivity().getSupportFragmentManager();
FragmentTransaction transaction2 = fm2.beginTransaction();
transaction2.replace(R.id.fragment1, fragment2);
transaction2.commit();
}
}
在你的主布局中,
<RelativeLayout 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"
tools:context=".ProfileActivity" >
<Button
android:id="@+id/button_profile_photos"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/relativeLayout3"
android:text="Photos" />
<Button
android:id="@+id/button_profile_group"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/button_profile_photos"
android:layout_alignBottom="@+id/button_profile_photos"
android:layout_toRightOf="@+id/button_profile_photos"
android:text="Groups" />
<FrameLayout
android:id="@+id/fragment1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_below="@+id/button_profile_photos" >
</FrameLayout>
和组片段,
public class GroupsFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflating layout
View v = inflater.inflate(R.layout.groups_fragment, container, false);
// We obtain layout references
return v;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
}
【讨论】:
第一个答案在技术上是正确的,但它会要求您为每个部分创建不同的片段类。如果其中有一些逻辑,您将需要以某种方式将这些片段连接到父片段/活动,这很烦人。我会坚持另一种解决方案 - 将一部分布局添加到现有布局中。 看到这个答案 How to add views dynamically to a RelativeLayout already declared in the xml layout?
【讨论】: