移动ImageView(Android)[重复]

问题描述 投票:0回答:1

这个问题在这里已有答案:

当用户点击ImageView时,我正试图测试设置GameView的位置。每当我点击模拟器时,应用程序崩溃时都没有任何错误消息。同样的结果,当我尝试setX / setYsetTop / 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);
    }
}
android android-layout imageview android-linearlayout layoutparams
1个回答
0
投票

我认为你应该在GameView类中设置更多的构造函数。 public class GameView extends LinearLayout { private ImageView flagImage;

 public GameView(Context context) {
    super(context);

    setBackgroundColor(Color.BLACK);
    flagImage = findViewById(R.id.flagImage);
}
public GameView(Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);

    setBackgroundColor(Color.BLACK);
    flagImage = findViewById(R.id.flagImage);
}
  public GameView(Context context, @Nullable AttributeSet attrs,@AttrRes int 
                  defStyleAttr) {
    super(context, attrs,defStyleAttr);

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

你可以将它的默认构造函数添加到类中。如果这不起作用,那么@ me。

© www.soinside.com 2019 - 2024. All rights reserved.