如何向通过编程生成的布局中添加一个碎片?

62

我有如下代码可以生成片段,但前提是我要将它们添加到一个已经存在于我的XML文件中的线性布局中。

LinearLayout fragmentsLayout = (LinearLayout) findViewById(R.id.foodItemActvity_linearLayout_fragments);
FragmentManager fragMan = getFragmentManager();
FragmentTransaction fragTransaction = fragMan.beginTransaction();

Fragment myFrag= new ImageFragment();
fragTransaction.add(R.id.foodItemActvity_linearLayout_fragments, myFrag , "fragment" + fragCount);
fragTransaction.commit();

现在如果我想将该片段添加到线性布局中,而该线性布局在XML文件中不存在,该怎么办?


LinearLayout rowLayout = new LinearLayout();

第二部分:

    Fragment frag1 = generateAppropriateFragment(type1);
    Fragment frag2 = generateAppropriateFragment(type2);

    LinearLayout fragmentsLayout = (LinearLayout) findViewById(R.id.foodItemActvity_linearLayout_fragments);
    LinearLayout rowLayout = new LinearLayout(this);
    rowLayout.setId(12345); // add counter to end

    fragmentsLayout.addView(rowLayout);     
    getFragmentManager().beginTransaction().add(rowLayout.getId(), frag1, "fragment_grandchild" + fragCount).commit();
    fragCount++;
    getFragmentManager().beginTransaction().add(rowLayout.getId(), frag2, "fragment_grandchild" + fragCount).commit();
    fragCount++;
2个回答

109

在某个时刻,我想你会将通过编程方式创建的LinearLayout添加到你在.xml文件中定义的根布局中。

这只是我的一个建议,可能有很多解决方案,但它是有效的:

简单地为通过程序创建的布局设置一个ID,并将其添加到你在.xml文件中定义的根布局中,然后使用该ID来添加Fragment。

代码示例:

LinearLayout rowLayout = new LinearLayout();
rowLayout.setId(whateveryouwantasid);
// add rowLayout to the root layout somewhere here

FragmentManager fragMan = getFragmentManager();
FragmentTransaction fragTransaction = fragMan.beginTransaction();   

Fragment myFrag = new ImageFragment();
fragTransaction.add(rowLayout.getId(), myFrag , "fragment" + fragCount);
fragTransaction.commit();

只需要选择您想要的整数值作为ID即可:

rowLayout.setId(12345);
如果您不只一次使用以上代码,最好找出一种创建唯一ID的方法,以避免重复。 更新: 以下是应该这样做的完整代码:(此代码已经过测试并且可用) 我将两个片段添加到具有水平方向的LinearLayout中,这样片段就会排在一起。请注意,我使用了固定高度和宽度为200dp,因此一个片段不会占用整个屏幕,就像使用“match_parent”一样。
MainActivity.java:
public class MainActivity extends Activity {

    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);     

        LinearLayout fragContainer = (LinearLayout) findViewById(R.id.llFragmentContainer);

        LinearLayout ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.HORIZONTAL);

        ll.setId(12345);

        getFragmentManager().beginTransaction().add(ll.getId(), TestFragment.newInstance("I am frag 1"), "someTag1").commit();
        getFragmentManager().beginTransaction().add(ll.getId(), TestFragment.newInstance("I am frag 2"), "someTag2").commit();

        fragContainer.addView(ll);
    }
}

TestFragment.java:

public class TestFragment extends Fragment {

    public static TestFragment newInstance(String text) {

        TestFragment f = new TestFragment();

        Bundle b = new Bundle();
        b.putString("text", text);
        f.setArguments(b);
        return f;
    }

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

        View v =  inflater.inflate(R.layout.fragment, container, false);

        ((TextView) v.findViewById(R.id.tvFragText)).setText(getArguments().getString("text"));     
        return v;
    }
}

activity_main.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rlMain"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="5dp"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <LinearLayout
        android:id="@+id/llFragmentContainer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="19dp"
        android:orientation="vertical" >
    </LinearLayout>
</RelativeLayout>

fragment.xml:

  <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="200dp"
    android:layout_height="200dp" >

    <TextView
        android:id="@+id/tvFragText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="" />

</RelativeLayout>

以下是上述代码的结果:(两个片段并排对齐)result


这正是我正在尝试做的事情!!唯一的问题是,我必须将id设置为什么?因为它需要一个整数,而通常在xml文件中,id是一个字符串? - Zapnologica
只需选择您想要的任何整数作为ID :) - Philipp Jahoda
4
很好的链接。以下是需要翻译的内容:"How can I assign an id to a view programmatically?" - Zapnologica
@Phil,我解决了编译问题,但是现在无法显示我的行布局。请看我的原始问题,我添加了第二部分即我的代码。它可以运行,但我看不到这两个片段。 - Zapnologica
11
我建议使用View.generateViewId()来生成视图ID。 - Jeremy Wiebe
显示剩余16条评论

0
以下是一个可用的代码,可以将一个片段(例如3次)添加到垂直LinearLayout(xNumberLinear)中。 您可以使用任何其他数字更改数字3,或从下拉列表中选择一个数字!
for (int i = 0; i < 3; i++) {
            LinearLayout linearDummy = new LinearLayout(getActivity());
            linearDummy.setOrientation(LinearLayout.VERTICAL);
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {

                Toast.makeText(getActivity(), "This function works on newer versions of android", Toast.LENGTH_LONG).show();

            } else {
                linearDummy.setId(View.generateViewId());
            }
            fragmentManager.beginTransaction().add(linearDummy.getId(), new SomeFragment(),"someTag1").commit();

            xNumberLinear.addView(linearDummy);
        }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接