android fragment onorientationchange问​​题

时间:2014-05-13 18:50:09

标签: android android-fragments

我创建了一个简单的项目Button Activity点击Toast显示Fragment。只需点击Button即可正常工作,但在更改方向并单击Button后发生错误。

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在定位后调用了Attach和onDetach。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:-1)

当设备Orientation更改时,默认情况下会破坏并再次创建片段所在的活动。您可以通过调整清单文件中的android:configChanges来避免这些更改。这段代码应该有效:

android:configChanges="keyboardHidden|orientation"