2014-05-13 43 views
0

我創建了一個簡單的項目,ButtonActivity單擊以顯示FragmentToast
只需點擊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定向之後。我該如何解決這個問題?

回答

-1

當設備方向更改時,片段所處的活動默認會被銷燬並重新創建。您可以通過調整清單文件中的android:configChanges來避免這些更改。此代碼應該工作:

android:configChanges="keyboardHidden|orientation"