android碎片onorientationchange问题

android碎片onorientationchange问题,android,android-fragments,Android,Android Fragments,我创建了一个简单的项目,活动中的按钮单击以显示来自片段的Toast。只需单击按钮即可正常工作,但在方向更改后,单击按钮会出现错误 public class MainActivity extends Activity { PlaceholderFragment pf; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setCont

我创建了一个简单的项目,活动中的按钮单击以显示来自片段的Toast。只需单击按钮即可正常工作,但在方向更改后,单击按钮会出现错误

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");
    }
}

}

我发现碎片在定向后调用了onAttach和onDetach。如何解决此问题?

当设备方向更改时,默认情况下,片段所在的活动将被销毁并再次创建。您可以通过调整清单文件中的android:configChanges来避免这些更改。此代码应适用于:

android:configChanges=键盘隐藏|方向