0
我創建了一個簡單的項目,Button
在Activity
單擊以顯示Fragment
Toast
。
只需點擊Button
即可正常工作,但方向改變後點擊Button
發生錯誤。android片段onorientationchange問題
public class MainActivity extends Activity {
PlaceholderFragment pf;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pf = new PlaceholderFragment();
Button b = (Button)findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
pf.showToast();
}
});
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, pf)
.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.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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
Log.i("TAG", "onCreateView");
return rootView;
}
public void showToast(){
Toast.makeText(getActivity(), "Show Toast from PlaceholderFragment", Toast.LENGTH_SHORT).show();
}
@Override
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
super.onAttach(activity);
Log.i("TAG", "onAttach");
}
@Override
public void onDetach() {
// TODO Auto-generated method stub
super.onDetach();
Log.i("TAG", "onDetach");
}
}
}
我發現Fragment
打電話onAttach和onDetach定向之後。我該如何解決這個問題?