我的.java
文件确实令人费解:当用户触摸屏幕时,我希望发生两件事。
在我的代码中,只会出现其中一个。以下是我的.java
文件。
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//**Part 1 begins here
final TextView textView = (TextView)findViewById(R.id.textView1);
final View touchLayout = findViewById(R.id.touchLayout);
touchLayout.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
textView.setText("Touch coordinates : " +
String.valueOf(event.getX()) + "x" + String.valueOf(event.getY()));
return true;
}
});
//**Part 1 ends here
//**Part 2 begins here
final TextView touchView = (TextView) findViewById(R.id.touchView);
final TextView viewLocat = (TextView)findViewById(R.id.viewLocat);
touchLayout.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
int[] viewLocation = new int[2];
touchView.getLocationOnScreen(viewLocation);
viewLocat.setText(String.valueOf(viewLocation[0]) + "x" + String.valueOf(viewLocation[1]));
return true;
}
});
}
//**Part 2 ends here
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
如果我运行这样的代码,则只发生第2部分(显示TextView
坐标,但未显示接触点坐标)。如果我使用//使第2部分静音,第1部分就完美了。我完全不知道为什么会发生这种情况,是否有人碰巧知道如何解决这个问题?
答案 0 :(得分:2)
您通过两次调用touchLayout.setOnTouchListener
来覆盖OnTouchListener。也许将代码从第一个监听器移到第二个监听器?
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView textView = (TextView)findViewById(R.id.textView1);
final View touchLayout = findViewById(R.id.touchLayout);
final TextView touchView = (TextView) findViewById(R.id.touchView);
final TextView viewLocat = (TextView)findViewById(R.id.viewLocat);
touchLayout.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
textView.setText("Touch coordinates : " +
String.valueOf(event.getX()) + "x" + String.valueOf(event.getY()));
int[] viewLocation = new int[2];
touchView.getLocationOnScreen(viewLocation);
viewLocat.setText(String.valueOf(viewLocation[0]) + "x" + String.valueOf(viewLocation[1]));
return true;
}
});
}