How to set the size and position of an image?

余生长醉 提交于 2019-12-25 03:37:11

问题


I am trying to set the size and position of an image (image2) on the screen so that it is in the same position and size relative to the background image (image1) it is on no matter the screen size. To do this, I try to alter the layout parameters of image2 in my onCreate method of my Activity class:

    public class Game_main extends Activity{


@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
     requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);



        ImageView image2= (ImageView) findViewById(R.id.seed1);
        ImageView image1= (ImageView) findViewById(R.id.board_rev1);


        RelativeLayout rl = (RelativeLayout) findViewById(R.id.rlGame);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams((image1.getWidth())/4, (image2.getHeight())/4);
        params.leftMargin = (image1.getWidth())/2;
        params.topMargin = (image1.getHeight())/4;
        rl.addView(image2, params);
        setContentView(R.layout.gamerev);


}


}

But when my app goes to this activity, I get an error that says the application has stopped unexpectedly. Then I have to force close the app. Why would this happen? Is there something I am missing? or is there a better way to do this?

The error in the logcat is:

E/AndroidRuntime( 296): java.lang.RuntimeException: Unable to start activity Co mponentInfo{com.soft.tobi/com.soft.tobi.Game_main}: java.lang.NullPointerExc eption

But I dont see why anything would be null because all the ids exist in my xml file:

<?xml version="1.0" encoding="utf-8"?>
  <RelativeLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:id="@+id/rlGame"
  >
    <ImageView android:layout_height="fill_parent" android:layout_width="fill_parent" android:id="@+id/board_rev1" android:src="@drawable/board_rev1"></ImageView>
    <ImageView android:id="@+id/seed1" android:src="@drawable/seed1" android:adjustViewBounds="true" android:layout_height="200dp" android:layout_marginTop="165dp" android:layout_width="200dp" android:layout_marginLeft="30dp"></ImageView>

</RelativeLayout>

Thanks


回答1:


Did you put a try catch block and try to debug it ? It seems to be something returns null..




回答2:


I think problem is size of imageview

 RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams((image1.getWidth())/4, (image2.getHeight())/4);

maybe it return 0 so this problem is occur..try it



来源:https://stackoverflow.com/questions/5905848/how-to-set-the-size-and-position-of-an-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!