【发布时间】:2018-03-04 23:10:01
【问题描述】:
当用户点击GameView 时,我正在尝试设置ImageView 的位置。每当我点击模拟器时,应用程序都会崩溃而没有任何错误消息。当我尝试 setX/setY 和 setTop/setLeft 时结果相同,我无法弄清楚我在这里缺少什么。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<com.example.test.GameView
android:id="@+id/groupLayout"
android:layout_width="300dp"
android:layout_height="300dp">
<ImageView
android:id="@+id/flagImage"
android:layout_width="100dp"
android:layout_height="100dp"
android:src="@drawable/flag"
/>
</com.example.test.GameView>
</LinearLayout>
public class GameView extends LinearLayout {
private ImageView flagImage;
public GameView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
setBackgroundColor(Color.BLACK);
flagImage = findViewById(R.id.flagImage);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
LayoutParams par = (LayoutParams)flagImage.getLayoutParams();
par.leftMargin += 30;
flagImage.setLayoutParams(par);
return super.onTouchEvent(event);
}
}
【问题讨论】:
-
ViewGroup的子Views 尚未添加到构造函数中。将您的findViewById()呼叫转移到onFinishInflate()。
标签: android android-layout imageview android-linearlayout layoutparams