0

I'm trying to test out setting the position of an ImageView when the user taps on the GameView. Whenever I tap on the emulator, the app crashes without any error messages. Same result for when I try setX/setY and setTop/setLeft I can't figure out what I'm missing here.

<?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);
    }
}
stumped
  • 3,235
  • 7
  • 43
  • 76
  • A `ViewGroup`'s child `View`s aren't yet added in the constructor. Move your `findViewById()` call to `onFinishInflate()`. – Mike M. Mar 05 '18 at 05:37

1 Answers1

0

I think you should set more constructors in your GameView class. 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);
}}

you can add its's default constructor into class. If this can't work,then @ me.