您好,我正在尝试编写一个程序,在设备处于纵向模式时可以显示一个片段,而在横向模式时可以显示另一个片段。我遇到了一些使代码无法正常工作的问题:
我使用了getWidth()和getHeight()来获取纵向和横向模式,但是这些功能在4.3中已被弃用,还可以使用其他什么功能呢?
我使用了replace()函数来显示我想要的片段,但是它被剔除为错误
完整的代码如下。您会发现我使用箭头和注释指出了错误的出处,因此您将确切地知道问题出在我的代码中。请查看我的代码并帮助我修复它。
公共类MainActivity扩展了ActionBarActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
//---get the current display info---
WindowManager wm = getWindowManager();
Display d = wm.getDefaultDisplay();
if (d.getWidth() > d.getHeight())//<----------these two functions get struck out as //an error
{
//---landscape mode---
Fragment1 fragment1 = new Fragment1();
// android.R.id.content refers to the content
// view of the activity
fragmentTransaction.replace( //<------this replace() function is seen as an //error
android.R.id.content, fragment1);
}
else
{
//---portrait mode---
Fragment2 fragment2 = new Fragment2();
fragmentTransaction.replace(//<------this replace() function is also seen as an //error
android.R.id.content, fragment2);
}
fragmentTransaction.commit();
**/
}
尝试在onCreate中使用这种模式。它更加干净,而且它使用适当的getSupportFragmentManager()代替了继承的受限对象getFragmentManager()
:
int currentOrientation = getResources().getConfiguration().orientation;
if (currentOrientation == Configuration.ORIENTATION_LANDSCAPE)
{
Fragment1 placeholder = new Fragment1();
placeholder.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, placeholder).commit();
} else
{
Fragment2 placeholder = new Fragment2();
placeholder.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, placeholder).commit();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句