这是我的mainActivity.java文件的代码

我正在尝试访问MyGestureListener类中的textview引用,但是我无法执行此操作,因为每次不幸的是,我的应用程序都停止了滚动手势。
这是我的代码

这是我的主班

公共类MainActivity扩展了AppCompatActivity {

TextView myText;
Button myButton;
private GestureDetectorCompat mDetector;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    myText = (TextView)findViewById(R.id.myText);
    myButton = (Button)findViewById(R.id.myButton);
    mDetector = new GestureDetectorCompat(this, new MyGestureListener());

    myButton.setOnClickListener(new Button.OnClickListener(){
        @Override
        public void onClick(View v) {
            myText.setText("I am clicked from button");
        }
    });

}

public TextView getTextView()
{

    TextView txtView = (TextView)findViewById(R.id.myText);
    return txtView;
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    this.mDetector.onTouchEvent(event);
    return super.onTouchEvent(event);
}


}

这是我的用户定义的类

类扩展了GestureDetector.SimpleOnGestureListener {

private TextView myText;
MainActivity m;

public MyGestureListener(){

    m = new MainActivity();


}
//MainActivity m = new MainActivity();
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {

    myText.setText("Scroll ho v ja hun");

    return true;
}


}

最佳答案

您不能像在MyGestureListener构造函数中那样自行创建任何Activity对象。它们是由Android创建的。

同样在MyGestureListener中,从未初始化TextView。

相反,在初始化MyGestureListener对象时,应该传递对TextView的引用。

例如,您可以执行以下操作:

public class MainActivity extends AppCompatActivity {

    TextView myText;
    Button myButton;
    private GestureDetectorCompat mDetector;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myText = (TextView)findViewById(R.id.myText);
        myButton = (Button)findViewById(R.id.myButton);
        mDetector = new GestureDetectorCompat(this, new MyGestureListener(myText));

        myButton.setOnClickListener(new Button.OnClickListener(){
            @Override
            public void onClick(View v) {
                myText.setText("I am clicked from button");
            }
        });

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        this.mDetector.onTouchEvent(event);
        return super.onTouchEvent(event);
    }
}

class MyGestureListener extends GestureDetector.SimpleOnGestureListener {

    private TextView myText;

    public MyGestureListener(TextView textView) {
        myText = textView;
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {

        myText.setText("Scroll ho v ja hun");

        return true;
    }
}

10-01 07:56