[英]I want to be able to get the screen height and width in Android
我正在嘗試獲取屏幕寬度和高度,以便在單擊按鈕時可以在屏幕上隨機移動按鈕。
到目前為止,我擁有的代碼是:public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
DisplayMetrics display = this.getResources().getDisplayMetrics();
int width = display.widthPixels;
int height = display.heightPixels;
public void moveMe(View view)
{
Button myButton = (Button) findViewById(R.id.my_button);
Random r = new Random();
int x = (r.nextInt(width));
int y = (r.nextInt(height));
myButton.setX(x);
myButton.setY(y);
}
}
XML是:
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<Button
android:id="@+id/my_button"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_x="0dp"
android:layout_y="0dp"
android:text="Yes"
android:onClick="moveMe"/>
</AbsoluteLayout>
但是,當我啟動該應用程序時,它說它已停止。
我在 Android Studio 中得到的錯誤是:
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.test.test/com.example.test.test.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
感謝您提供的任何幫助。
您在調用super.onCreate(Bundle)
之前調用getResources()
。 您必須在onCreate()
之后調用getResources()
onCreate()
。 將您的代碼移動到onCreate
或onStart
:
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DisplayMetrics display = getResources().getDisplayMetrics();
int width = display.widthPixels;
int height = display.heightPixels;
}
在onCreate
試試這個:
DisplayMetrics display = this.getResources().getDisplayMetrics();
int width = display.widthPixels;
int height = display.heightPixels
您可以使用代碼,以便在布局完全呈現之前無需加權。
Display display = context.getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int height = size.y;
int width = size.x;
但在實踐中,AbsoluteLayout 已被棄用,它使用絕對定位來定位 Children 的不好方法可能不會在所有設備中提供相同的用戶界面感覺。專家建議的其他選項是 RelativeLayout。
您可以在鏈接絕對定位陷阱中找到AbsoluteLayout 的缺點
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.