扩展Android Fragment类时出现错误

2020年5月21日 78点热度 0条评论 来源: Peter Hua

编译下面的代码时出现此错误。 Android工作室还警告说,Fragment只支持API级别11及以上。扩展Android Fragment类时出现错误


Error:(16, 21) error: no suitable method found for add(int,ForecastFragment) 
method FragmentTransaction.add(int,Fragment,String) is not applicable 
(actual and formal argument lists differ in length) 
method FragmentTransaction.add(int,Fragment) is not applicable 
(actual argument ForecastFragment cannot be converted to Fragment by method invocation conversion) 
method FragmentTransaction.add(Fragment,String) is not applicable 
(actual argument int cannot be converted to Fragment by method invocation conversion) 

代码:

public class MainActivity extends ActionBarActivity { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    if (savedInstanceState == null) { 
     getSupportFragmentManager().beginTransaction() 
       .add(R.id.container, new ForecastFragment()) 
       .commit(); 
    } 
} 


public class ForecastFragment extends Fragment { 
private static final String TAG = ForecastFragment.class.getSimpleName(); 
private ArrayAdapter<String> mForecastAdapter; 

public ForecastFragment() { 
} 

===========解决方案如下:

您应该从支持库使用片段类。 检查您的进口部分。你的代码应该看起来像这样:

import android.os.Bundle; 
import android.support.v4.app.Fragment; 
import android.support.v7.app.ActionBarActivity; 
import android.widget.ArrayAdapter; 


public class MainActivity extends ActionBarActivity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     if (savedInstanceState == null) { 
      getSupportFragmentManager().beginTransaction() 
        .add(R.id.container, new ForecastFragment()) 
        .commit(); 
     } 
    } 

    public static class ForecastFragment extends Fragment { 
     private final String TAG = ForecastFragment.class.getSimpleName(); 
     private ArrayAdapter<String> mForecastAdapter; 

     public ForecastFragment() { 
     } 
    } 
} 
    原文作者:Peter Hua
    原文地址: https://stackoverflow.com/q/29681998
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系管理员进行删除。