package com.example.**.beatle.app;
import android.app.Fragment;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends FragmentActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(savedInstanceState==null)
{
getSupportFragmentManager().beginTransaction().add(R.id.container, new PlaceholderFragment()).commit();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class PlaceholderFragment extends Fragment {
private ArrayAdapter<String> mForecastAdapter;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
String[] forecastArray = {"Today-Sunny-88/63", "Tommorrow-windy-88/94", "wed-aloo-alooo"};
List<String> weekForecast = new ArrayList<String>(Arrays.asList(forecastArray));
mForecastAdapter = new ArrayAdapter<String>(getActivity(), R.layout.fragment_main, R.id.list_item_forecast_textview, weekForecast);
ListView listView = (ListView) rootView.findViewById(R.id.list_view_forecast);
listView.setAdapter(mForecastAdapter);
return rootView;
}
}}
消息Gradle Build 错误:(27,59)错误:找不到合适的add方法(int,PlaceholderFragment) 方法FragmentTransaction.add(Fragment,String)不适用 (参数不匹配; int无法转换为Fragment) 方法FragmentTransaction.add(int,Fragment)不适用 (参数不匹配; PlaceholderFragment无法转换为Fragment) 注意:某些消息已经简化;使用-Xdiags重新编译:详细以获得完整输出 错误:任务':app:compileDebugJava'的执行失败。 编译失败;有关详细信息,请参阅编译器错误输出。
答案 0 :(得分:39)
您正在使用FragmentActivity
和getSupportFragmentManager()
。因此,PlaceholderFragment
需要继承android.support.v4.app.Fragment
,而不是android.app.Fragment
。
答案 1 :(得分:3)
使用
import android.support.v4.app.Fragment;
而不是
import android.app.Fragment;
项目全部。
另外,使用FragmentManager和FragmentTransaction的支持库。
答案 2 :(得分:0)
如果您使用Andorid Jetpack的 AndroidX ,请使用
androidx.fragment.app.Fragment
而不是
import android.app.Fragment;
// or
import android.support.v4.app.Fragment;