【问题标题】:Moving an ImageView on tap (Android) [duplicate]在点击时移动 ImageView(Android)[重复]
【发布时间】:2018-03-04 23:10:01
【问题描述】:

当用户点击GameView 时,我正在尝试设置ImageView 的位置。每当我点击模拟器时,应用程序都会崩溃而没有任何错误消息。当我尝试 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);
    }
}

【问题讨论】:

  • ViewGroup 的子 Views 尚未添加到构造函数中。将您的 findViewById() 呼叫转移到 onFinishInflate()

标签: android android-layout imageview android-linearlayout layoutparams


【解决方案1】:

我认为您应该在 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);
}}

您可以将其默认构造函数添加到类中。如果这不起作用,那么@我。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-30
    • 1970-01-01
    • 1970-01-01
    • 2011-03-24
    • 1970-01-01
    • 1970-01-01
    • 2014-05-29
    • 2015-02-03
    相关资源
    最近更新 更多