我想將片段添加到以編程方式實現其佈局的活動。我查看了Fragment文檔,但沒有很多例子描述我需要什麼。下面是我試着寫的代碼類型:如何使用以編程方式創建的內容視圖向活動添加片段
public class DebugExampleTwo extends Activity {
private ExampleTwoFragment mFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FrameLayout frame = new FrameLayout(this);
if (savedInstanceState == null) {
mFragment = new ExampleTwoFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(frame.getId(), mFragment).commit();
}
setContentView(frame);
}
}
...
public class ExampleTwoFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
Button button = new Button(getActivity());
button.setText("Hello There");
return button;
}
}
此代碼編譯,但在開始崩潰,可能是因爲我的FragmentTransaction.add()
不正確。什麼是正確的方法來做到這一點?
如果您只想使用片段作爲活動的頂級內容視圖,那麼您可以使用'ft.add(android.R.id.content,newFragment)'。如果片段的容器不是活動的內容視圖,則只需創建自定義佈局並設置其ID。 – 2011-03-02 00:11:32
而不是硬編碼的id,你可以[定義它在XML](http://developer.android.com/guide/topics/resources/more-resources.html#Id)並引用它爲正常(R.id 。我的身份)。 – 2011-03-02 01:58:22
@JasonHanley如果我將創建許多視圖,你知道我將如何以編程方式生成許多獨特的視圖ID嗎? – 2011-03-03 07:05:26