我想要獲得屏幕寬度和高度,以便我可以使按鈕在屏幕上隨機移動,當我單擊它時。我想能夠在Android中獲取屏幕高度和寬度
我到目前爲止的代碼吧: 公共類MainActivity擴展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
三江源,你可以提供任何幫助。
[以像素爲單位獲取屏幕尺寸(可能的重複http://stackoverflow.com/questions/1016896/get-screen-dimensions-in-pixels找到AbsoluteLayout的缺點) – Varun