繁体   English   中英

如何设置图像的大小和位置?

[英]How to set the size and position of an image?

我正在尝试在屏幕上设置图像(image2)的大小和位置,以便无论屏幕大小如何,它相对于背景图像(image1)都处于相同的位置和大小。 为此,我尝试在Activity类的onCreate方法中更改image2的布局参数:

    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);


}


}

但是,当我的应用程序执行此活动时,我收到一条错误消息,指出该应用程序已意外停止。 然后,我必须强制关闭该应用程序。 为什么会这样? 我有什么想念的吗? 还是有更好的方法来做到这一点?

logcat中的错误是:

E / AndroidRuntime(296):java.lang.RuntimeException:无法启动活动Co mponentInfo {com.soft.tobi / com.soft.tobi.Game_main}:java.lang.NullPointerExc eption

但我不明白为什么任何东西都为null,因为所有id都存在于我的xml文件中:

<?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>

谢谢

我认为问题是imageview的大小

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

也许它返回0,所以会出现此问题。

您是否放置了try catch块并尝试对其进行调试? 似乎是返回null的东西。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM