【发布时间】:2015-03-16 15:59:41
【问题描述】:
我正在阅读这本“开始 Android 开发”一书。我到了 Fragments 部分并按照所示代码进行操作,但是我的编译器给了我一个错误。 MainActivity.java 包 com.example.fragmentsdemo;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MainActivity extends Activity {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle saveInstanceState){
View view = inflater.inflate(R.layout.my_frag, null, false);
return view;
}
}
错误从“公共视图”开始,并指出“MainActivity.java 类型的方法...必须覆盖或实现超类型方法
下面两个 XML 文件供补全...
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<fragment
android:id="@+id/fragment1"
android:name="com.example.fragmentsdemo.MyFragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
tools:layout="@layout/my_frag" />
</RelativeLayout>
my_frag.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">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World from Fragment!"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
现在,当我删除 @Override 时,它会运行,但我没有看到文本“Hello World from Fragment!”那里。有什么建议吗?
【问题讨论】:
-
你是在创建一个Activity还是一个Fragment?如果那是你正在构建的,你应该扩展 Fragment
-
Activity 类是否包含带有签名
View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle saveInstanceState)的公共或受保护方法? -
我确实注意到我输入了 Activity 而不是 Fragment(可能是自动驾驶),在更改之后没有任何改变。我收到相同的错误消息。我不确定您对公共或受保护方法的含义。您看到的整个代码就是要从书中运行的内容。
-
@Crazylegs888 你的活动应该覆盖
onCreate这样的方法 -->@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // your code here }。我建议您使用 Eclipse 或 Android Studio 创建活动(而不是从书中复制粘贴),因为它会自动创建您需要的方法。
标签: java android methods overriding