我试图将一些复选框动态地设置到我的片段布局中,但是我无法获取它。请需要一些帮助,这是我第一次处理片段,我有点迷失了。

谢谢大家

我在下面发布我的代码:

MainActivity.java:

 public class MainActivity extends FragmentActivity {

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

    LinearLayout fragContainer = (LinearLayout) findViewById(R.id.pasosLayout);
    LinearLayout pasosLayout = new LinearLayout(this);
    pasosLayout.setOrientation(LinearLayout.VERTICAL);
    pasosLayout.setId(12345);

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


    fragContainer.addView(pasosLayout);

   }
 }


TestFragment.java:

   public class TestFragment extends Fragment {

   public static android.app.Fragment 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;
}
}


最后是我的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>

最佳答案

您要在片段交易后将pasosLayout添加到fragContainer
因此,首先将pasosLayout添加到fragContainer,还应该将layoutParams设置为pasosLayout

public class MainActivity extends FragmentActivity {

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

        LinearLayout fragContainer = (LinearLayout) findViewById(R.id.pasosLayout);
        LinearLayout pasosLayout = new LinearLayout(this);

        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                       ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        pasosLayout.setLayoutParams(layoutParams);

        pasosLayout.setOrientation(LinearLayout.VERTICAL);
        pasosLayout.setId(12345);


        fragContainer.addView(pasosLayout);

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

    }
}

09-05 14:40