如何将片段添加到以编程方式生成的布局? [英] How to add a fragment to a programmatically generated layout?

查看:21
本文介绍了如何将片段添加到以编程方式生成的布局?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码可以生成片段,但前提是我将它们添加到我的 XML 文件中存在的线性布局中.

LinearLayout fragmentLayout = (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();

第 2 部分:

 Fragment frag1 = generateAppropriateFragment(type1);片段 frag2 = generateAppropriateFragment(type2);LinearLayout fragmentLayout = (LinearLayout) findViewById(R.id.foodItemActvity_linearLayout_fragments);LinearLayout rowLayout = new LinearLayout(this);rowLayout.setId(12345);//将计数器添加到末尾fragmentLayout.addView(rowLayout);getFragmentManager().beginTransaction().add(rowLayout.getId(), frag1, "fragment_grandchild" + fragCount).commit();fragCount++;getFragmentManager().beginTransaction().add(rowLayout.getId(), frag2, "fragment_grandchild" + fragCount).commit();fragCount++;

解决方案

在某个时候,我想您会将以编程方式创建的 LinearLayout 添加到您在 .xml 中定义的某个根布局中.这只是我的一个建议,可能是许多解决方案之一,但它有效:只需为以编程方式创建的布局设置一个 ID,并将其添加到您在 .xml 中定义的根布局,然后使用设置的 ID 添加片段.

它可能看起来像这样:

LinearLayout rowLayout = new LinearLayout();rowLayout.setId(whateveryouwantasid);//将 rowLayout 添加到此处某处的根布局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 的方法 可能是明智之举,以便避免重复>.

更新:

这是应该如何完成的完整代码:(此代码经过测试并有效)我将两个 Fragment 添加到具有水平方向的 LinearLayout,导致 Fragments 彼此相邻对齐.另请注意,我使用了 200dp 的固定高度和宽度,因此一个 Fragment 不会像match_parent"那样使用全屏.>

MainActivity.java:

public class MainActivity extends Activity {@SuppressLint("NewApi")@覆盖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 {公共静态 TestFragment newInstance(String text) {TestFragment f = new TestFragment();捆绑 b = 新捆绑();b.putString("text", text);f.setArguments(b);返回 f;}@覆盖公共视图 onCreateView(LayoutInflater inflater,ViewGroup 容器,Bundle savedInstanceState) {查看 v = inflater.inflate(R.layout.fragment, container, false);((TextView) v.findViewById(R.id.tvFragText)).setText(getArguments().getString("text"));返回 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"机器人:填充=5dp"工具:context=".MainActivity" ><文本视图android:id="@+id/textView1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="@string/hello_world"/><线性布局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"机器人:方向=垂直"></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" ><文本视图android:id="@+id/tvFragText"android:layout_width="wrap_content"android:layout_height="wrap_content"机器人:layout_centerHorizo​​ntal="true"机器人:layout_centerVertical =真"机器人:文本="/></RelativeLayout>

这是上面代码的结果:(两个Fragment是挨着对齐的)

I have the following code working which generates fragments, but only if I am adding them to a linear layout which exists in my XML file.

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();

Now what if I want to add that fragment to a linear layout that does not already exist in the XML file such as

LinearLayout rowLayout = new LinearLayout();

Part 2:

    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++;

解决方案

At some point, I suppose you will add your programatically created LinearLayout to some root layout that you defined in .xml. This is just a suggestion of mine and probably one of many solutions, but it works: Simply set an ID for the programatically created layout, and add it to the root layout that you defined in .xml, and then use the set ID to add the Fragment.

It could look like this:

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();

Simply choose whatever Integer value you want for the ID:

rowLayout.setId(12345);

If you are using the above line of code not just once, it would probably be smart to figure out a way to create unique-IDs, in order to avoid duplicates.

UPDATE:

Here is the full code of how it should be done: (this code is tested and works) I am adding two Fragments to a LinearLayout with horizontal orientation, resulting in the Fragments being aligned next to each other. Please also be aware, that I used a fixed height and width of 200dp, so that one Fragment does not use the full screen as it would with "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>

And this is the result of the above code: (the two Fragments are aligned next to each other)

这篇关于如何将片段添加到以编程方式生成的布局?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆