gpt4 book ai didi

Android:更改 fragment 中的layout.xml

转载 作者:行者123 更新时间:2023-11-29 02:02:48 25 4
gpt4 key购买 nike

我有两个并排的 fragment 。当我对左侧 fragment 执行操作时,我希望右侧 fragment 发生变化。只要正确 fragment 的 layout.xml 没有改变,它就可以工作。我想要的是定义一些布局,例如layout1.xml、layout2.xml 等 根据左侧发生的情况,右侧应显示这些布局之一。我找到了 http://developer.android.com/guide/components/fragments.html#Transactions但我不确定这是否是正确的方法。如果不是,正确的方法是什么?如果是的话,我有点挣扎

transaction.replace(R.id.fragment_container, newFragment);

我需要告诉 newFragment 它现在有,例如layout27.xml。我该怎么做?

编辑:

我的 main.xml 看起来像这样

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >


<fragment class="com.whatever.OverviewFragment"
android:id="@+id/list"
android:name="com.whatever.OverviewFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1" />

<fragment class="com.whatever.DetailFragment"
android:id="@+id/listB"
android:name="com.whatever.DetailFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1" />

</LinearLayout>

第二个 fragment 应该根据用户操作进行交换,对于 listB,我假设有 5 个不同的 layout.xml 文件。

DetailFragment.java 基本上是这样的:

public  class DetailFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.details, container, false);
}

//this is called when I do an action in the other fragment
public void setScreen(int id) {
//This fragment is one of the 5 possible fragments
DetailFragment2 newF = new DetailFragment2();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.listB, newF);
transaction.addToBackStack(null);
transaction.commit();
}
}

最佳答案

我做了类似的事情,使用 fragment 参数来传递要选择的布局

fragment 1(对照)

Bundle data = new Bundle();
data.putInt("LayoutChoice",i); // i chooses which layout to use on fragment 2
Fragment f = new Fragment2();
f.setArguments(data);
fragmentTransaction.replace(R.id.fcontainer, f);

fragment 2(显示)

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

switch( getArguments().getInt("LayoutChoice") ) {
case 1:
rootView = inflater.inflate(R.layout.layout1, container, false);
break;
case 2:
rootView = inflater.inflate(R.layout.layout2, container, false);
break;
}

关于Android:更改 fragment 中的layout.xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11674270/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com