扩展Android Fragment类时出现错误
编译下面的代码时出现此错误。 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() {
}
}
}
以上是 扩展Android Fragment类时出现错误 的全部内容, 来源链接: utcz.com/qa/264957.html