以下是我的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;
}
}
答案 0 :(得分:1)
您不能像在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;
}
}
答案 1 :(得分:0)
您永远不会设置myText MyGestureListener类。试试这个:
myText = (TextView)findViewById(R.id.myText);
mDetector = new GestureDetectorCompat(this, new MyGestureListener());
mDetector.myText = myText;
对于上面的代码,myText必须是公开的。
所以改变这个: 私有TextView myText;
到此:
public TextView myText;