I am trying to get the screen width and height so that I can make a button move randomly on the screen when I click it.
The code I have so far it: 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);
}
}
The XML is:
<?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>
However, when I launch the app it says that it has stopped.
The error I get in Android Studio is:
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
Thankyou for any help you can offer.
You are calling getResources()
before the super.onCreate(Bundle)
is called. You must call getResources()
after onCreate()
. Move your code to onCreate
or 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;
}
Try this inside onCreate
:
DisplayMetrics display = this.getResources().getDisplayMetrics();
int width = display.widthPixels;
int height = display.heightPixels
You can use code so that no need to weight till your layout get rendered completely.
Display display = context.getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int height = size.y;
int width = size.x;
But in practice AbsoluteLayout is deprecated and its not good way to position Children using absolute positioning may not give same User Interface feel in all devices.Other option suggested by experts is RelativeLayout.
You can find downside of the AbsoluteLayout at the link Absolute positioning pitfalls
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.