android – 我应该使用什么代替getWidth()和getHeight()来知道宽度何时更大以及何时高度更大
作者:互联网
参见英文答案 > Get screen dimensions in pixels 39个
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Display;
import android.view.WindowManager;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fm=getFragmentManager();
FragmentTransaction ft= fm.beginTransaction();
WindowManager wm= getWindowManager();
Display d=wm.getDefaultDisplay();
if (d.getWidth()>d.getHeight())
{
Fragment1 f1 = new Fragment1();
ft.replace(android.R.id.content, f1);
}
else
{
Fragment2 f2 = new Fragment2();
ft.replace(android.R.id.content, f2);
}
ft.commit();
}
}
我想在android中使用片段,并且当显示的宽度大于显示的高度时想要显示fragment1,当显示的高度大于显示的宽度时,想要显示fragment2但是当使用getWidth()和getHeight()时,android studio会说这些方法都被贬低了.
那么如何知道宽度何时更大以及何时高度更大?
解决方法:
使用DisplayMetrics而不是Display.
试试这个:
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Display;
import android.view.WindowManager;
import android.util.DisplayMetrics;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fm=getFragmentManager();
FragmentTransaction ft= fm.beginTransaction();
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int height = displayMetrics.heightPixels;
int width = displayMetrics.widthPixels;
if (width > height)
{
Fragment1 f1 = new Fragment1();
ft.replace(android.R.id.content, f1);
}
else
{
Fragment2 f2 = new Fragment2();
ft.replace(android.R.id.content, f2);
}
ft.commit();
}
}
标签:android,fragment,display,window-managers,fragmentmanager 来源: https://codeday.me/bug/20190716/1474544.html