所以,这是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;
}
}
}
答案 0 :(得分:1)
这是错误的
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();
}
答案 1 :(得分:0)
如果你对困惑的片段感到困惑,你就不应该把所有这些事情联系起来,在你完全感到舒服的情况下,将它们分开来做:
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();