方法不会覆盖其超类的方法

时间:2016-04-27 17:23:01

标签: java android override superclass

有谁能告诉我,为什么会出现这个错误(甚至有更好的解决方案)? 我是Java(和Android)开发的新手,所以我真的不知道我的错 我的代码:

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;


public class select_type extends Fragment {


    public select_type() {
        // Required empty public constructor
    }

    @Override //<--- Cause the ERROR
    public View onCreateView(View view, LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        return inflater.inflate(R.layout.fragment_select_type, container, false);

        Button btn = (Button) view.findViewById(R.id.btn);

        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                noVIP TextFragment = new noVIP();
                FragmentTransaction transaction = getFragmentManager().beginTransaction();
                transaction.replace(R.id.fragment_container, TextFragment);
                transaction.addToBackStack(null);
                transaction.commit();
            }
        });

        return view;
    }

}

2 个答案:

答案 0 :(得分:3)

替换:

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

使用:

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

onCreateView() is not passed a View parameter

另外,摆脱super.onViewCreated(view, savedInstanceState);。在你所在的地方打电话既不必要也不恰当。

请注意,由于您首先返回,因此该方法中return语句之后的所有内容都不会被执行。将inflater.inflate(...)结果分配给局部变量,使用它,然后在方法结束时返回该变量。

答案 1 :(得分:1)

您也可以覆盖两种方法:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_select_type, container, false);
}




@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

   Button btn = (Button) view.findViewById(R.id.btn);

    btn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            noVIP TextFragment = new noVIP();
            FragmentTransaction transaction = getFragmentManager().beginTransaction();
            transaction.replace(R.id.fragment_container, TextFragment);
            transaction.addToBackStack(null);
            transaction.commit();
        }
    }); 

  }