画面の幅と高さを取得しようとしているため、クリックすると画面上をランダムに移動できます。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
ありがとう。
可能な複製をAbsoluteLayoutの欠点を見つけることができます(http://stackoverflow.com/questions/1016896/get-screen-dimensions-in-pixels ) – Varun