我正在尝试去一个特定的片段,我在Activity中初始化它。但我的屏幕上没有任何错误,但在我的设备上,我的应用程序停止运行,他没有进入Fragment。可能是什么问题? Thanx为你提供帮助。您可以在下面找到我的代码:
public class SubCatActivity extends Activity {
int hoofdCat;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_subcat);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.replace(R.id.container, new SubCatFragment())
.commit();
}
hoofdCat = Integer.parseInt(getIntent().getStringExtra("hoofdCat"));
}
public int getHoofdCat(){return hoofdCat;}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.info, 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);
}
我的片段:
public class SubCatFragment extends Fragment implements SubCatFragmentInteractionListener {
private SubCatFragmentInteractionListener mListener;
public SubCatFragment(){
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_subcat, container, false);
ListView lstSubcat = (ListView) rootView.findViewById(R.id.lvSubcat);
ArrayList<String> subcat = new ArrayList<String>();
SubCatActivity activity = (SubCatActivity)getActivity();
int hoofdcat =activity.getHoofdCat();
DBAdapter db = new DBAdapter(getActivity().getBaseContext());
db.open();
Cursor c = db.getAllSubcat(hoofdcat);
if(c.moveToFirst())
{
do{
subcat.add(c.getString(1));
}while (c.moveToNext());
}
db.close();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, subcat);
lstSubcat.setAdapter(adapter);
lstSubcat.setOnItemClickListener(lstSubcatItemClickListener);
return rootView;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (SubCatFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement HoofdCatFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
private ListView.OnItemClickListener lstSubcatItemClickListener = new ListView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
//mListener.showSubCatActivity(pos+1);
}
};
}
答案 0 :(得分:1)
答案 1 :(得分:0)
在onPostCreate中替换或添加片段,而不是onCreate。