谢谢。
我将代码发布如下:
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>
答案 0 :(得分:0)
您要在片段交易后将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();
}
}
答案 1 :(得分:0)
您不需要通过片段添加视图...只需填充视图,填充其数据,然后直接将其添加到容器中即可。
View checkbox = inflater.inflate(R.layout.fragment, fragContainer, false);
TextView text = checkbox.findViewById(R.id.tvFragText);
text.setText("My cool text");
fragContainer.addView(checkbox);