如何正确使用带有片段的活动?

时间:2015-04-08 16:16:34

标签: java android android-fragments android-view

我正在尝试使用Activity来使用Fragment(稍后我将使用更多片段)。我为这样的Fragment创建了一个类和一个布局,并将它们包含在Activity的布局中。

这就是我的Activity课程的样子:

public class Expressa extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

这就是我的Fragment课程的样子:

public class MessageFragment extends Fragment {

    EditText messageField;
    private onNewMessageListener  listener;

    public View OnCreateVie(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.message_fragment_layout,container,false);

         messageField = (EditText) view.findViewById(R.id.messageField);

        return view;
    }

    public void doTextToSpeech(View view) {

        String text = messageField.getText().toString().trim();
        new TextToSpeechServices().execute(text);
    }

    public interface onNewMessageListener {

        public void newMessage(String msg);

    }

}

布局

Activity布局:

LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:baselineAligned="false"
    android:orientation="vertical" >

    <fragment
        android:id="@+id/messageFragment"
        class="apps.android.expressa.expressa.MessageFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        tools:layout="@layout/message_fragment_layout" />
</LinearLayout>

片段的:

但是,我总是收到IllegalStateException抱怨MessageFragment没有创建视图。

这是fragment's layout,这是complete stacktrace。我正在使用编译SDK API 22,构建工具版本21.1.2和min SDK是16。 我有什么问题?

1 个答案:

答案 0 :(得分:1)

引发IllegalStateException,因为Android未在onCreateView()中检测到MessageFragment的实施。您拼错了onCreateView()方法的名称。

替换

public View OnCreateVie(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)

使用正确的方法签名和@Override注释,框架将正确解释您为View指定了Fragment