我正在尝试在屏幕上设置图像(image2)的大小和位置,使其相对于背景图像(image1)处于相同的位置和大小,无论屏幕大小如何。为此,我尝试在我的班级onCreate
方法中更改 image2 的布局参数:Activity
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:无法启动活动组件信息{com.soft.tobi/com.soft.tobi.Game_main}:java.lang.NullPointerExc eption
但我不明白为什么任何东西都会为空,因为所有 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>
谢谢