OnTouchListener on Activity never calls
I used this code, but when i click on activity at runtime, it never hits in OnTouch() method. Can someone guide me what i am doing wrong? Should i need to setcontentview of this activity? Actually i want the coordinates of activity where user touch during execution.
public class TouchTestAppActivity extends Activity implements OnTouchListener
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//setContentView(R.layout.touch);
}
@Override
public boolean onTouch(View arg0, MotionEvent arg1)
{
// TODO Auto-generated method stub
String tes开发者_开发技巧t = "hello";
}
}
UPDATE:
You need to do this :
- In your XML layout file, you need an ID for the root view:
android:id="@+id/myView"
In youer onCreate() method, write this:
LinearView v= (LinearView) findViewById(R.id.myView); v.setOnTouchListener(this);
Assuming that your root view is a LinearView
You should the onTouchListener to relevant GUI components.
For example:
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.touch);
TextView someView = (TextView)findViewById(R.id.some_view_from_layout_xml);
someView.setOnTouchListener(this); // "this" is the activity which is also OnTouchListener
}
You have to add a the listener using setOnTouchListener()
otherwise who will give call to your onTouch method. any listener works on any view. so you have to add the listener to the view eg button.setOnTouchListener(this);
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View vi = inflater.inflate(R.layout.yourxml, null);
setCOntentView(vi);
vi.setOnTouchListener(this);
In onCreate, you need to set the content view (just uncommenting the second line should probably work) and then you need to set your OnTouchListener (your activity) as the onTouchListener for a view in your application.
Let's say you've got a view in your layout called "MainView"; it would look something like this:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
View view = findViewById(R.id.MainView);
view.setOnTouchListener(this);
}
This article has a good example: http://www.zdnet.com/blog/burnette/how-to-use-multi-touch-in-android-2-part-2-building-the-touch-example/1763
精彩评论