所以,这里是myActivity.java
基本上,当我尝试使用commit()时,onCreate方法中出现了一个错误所以,只是不确定为什么会这样。可能需要一些指导。谢谢
此外,作为一个碎片的初学者,我有时会有点困惑。
它告诉我它"无法解析方法commit()"。
public class MyActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new ForecastFragment()
.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.my, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A Forecast fragment containing a simple view.
*/
public static class ForecastFragment extends Fragment {
private ArrayAdapter<String> mForecastAdapter;
public ForecastFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_my, container, false);
String[] forecastArray={
"Right Now - Hot. Grab a Lemonade!",
"Today - Boiling! Feels more like a Heat Furnace!",
"Tomorrow - Rains! Carry an Umbrella!",
"Tuesday - Hailstones!",
"Wednesday - Stormy",
"Thursday - Snowfall!",
"Friday - Rebecca Black",
"Saturday - Thunder!",
"Sunday - Just right." };
List<String>weekForecast=new ArrayList<String>(Arrays.asList(forecastArray));
mForecastAdapter = new ArrayAdapter<String>(
getActivity(),
R.layout.list_item_forecast,
R.id.list_item_forecast_textview,
weekForecast);
ListView listView=(ListView) rootView.findViewById(R.id.listview_forecast);
listView.setAdapter(mForecastAdapter);
return rootView;
}
}
}
这是错误的
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new ForecastFragment().
commit()); //<-----
}
commit()
是FragmentTransaction
上的方法,而不是Fragment
上的方法。因此,将您的代码更改为:
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new ForecastFragment())
.commit();
}
如果你对混淆的片段感到困惑,你不应该将所有这些东西串联起来,在单独的行中进行,直到你完全舒服为止:
getFragmentManager().beginTransaction()
.add(R.id.container, new ForecastFragment()
.commit();
成为
ForecastFragment newFragment = new ForecastFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.add(R.id.container, newFragment );
transaction.addToBackStack(null);
transaction.commit();