2016-04-27 115 views
2

任何人都可以告訴我,爲什麼會顯示此錯誤(或者甚至有更好的解決方案)?
我是新來的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; 
    } 

} 

回答

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(); 
     } 
    }); 

    } 
2

替換:

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

有:

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

as onCreateView() is not passed a View parameter

另外,擺脫super.onViewCreated(view, savedInstanceState);。在你所在的地方打電話既不必要也不合適。

請注意,該方法中的return語句後的所有內容都不會執行,因爲您首先返回。將inflater.inflate(...)結果賦值給一個局部變量,使用它,然後在方法結束時返回該變量。

+0

好了,但現在,我怎樣才能使'按鈕BTN =(按鈕)view.findViewById(R.id.btn)'? – NiklasZeroZero

+1

@NiklasZeroZero:將'inflater.inflate(...)'結果賦值給一個局部變量。隨意調用這個'View''view''。然後,在'view'上調用'findViewById()'。 – CommonsWare

相關問題