我有一个简单的片段:
public class InputFragment extends Fragment{
public View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
return inflater.inflate(R.layout.input_fragment, container, false);
}
}
在xml中定义如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<EditText
android:id="@+id/ttsInput"
android:layout_width="228dp"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:layout_width="80dp"
android:layout_height="wrap_content"
android:text="GO" />
</LinearLayout>
我将它添加到我的主要活动中:
package com.example.texttospeechapp;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(findViewById(R.id.fragment_container) != null){
InputFragment inputFrag = new InputFragment();
inputFrag.setArguments(getIntent().getExtras());
getFragmentManager().beginTransaction().add(R.id.fragment_container, inputFrag);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
这是主要活动的 XML:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
行为:
- 活动加载时不会崩溃,但不显示片段 ui。
我只是进入碎片。我不确定为什么这不起作用(我只是按照教程@ http://developer.android.com/training/basics/fragments/fragment-ui.html)