view.performClick()觸發點擊事件,performclick
1、主要作用
自動觸發控制項的點擊事件
2、介面的布局檔案 activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <Button android:id="@+id/bt" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="點擊一下" /> <Button android:id="@+id/bt2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/bt" android:text="@string/hello_world" /></RelativeLayout>
3、MainActivity 代碼
package com.android;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.Toast;public class MainActivity extends Activity { Button button1 ; Button button2 ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main ); button1 = (Button) findViewById( R.id.bt ) ; button1.setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { button2.performClick(); //調用 button2的點擊事件 } }); button2 = (Button) findViewById( R.id.bt2 ) ; button2.setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { Toast.makeText( MainActivity.this , "點擊了", Toast.LENGTH_SHORT).show(); } }); }}
4、注意事項
如果同時使用了view.setOnTouchListener()方法,則有可能存在攔截view.performClick()的響應事件,
因為當view.OnTouchEvent()在event.getAction() == MotionEvent.ACTION_DOWN時返回false,
系統會認為view不需要處理Touch事件,則後續的Touch事件(move、up、click)就不會被傳進來 。
所以也不會觸發view.performClick(),而view.setOnTouchListener()相當於是重寫了view.OnTouchEvent(),
所以在寫view的TouchListener處理時,需要留意view是否存在點擊事件監聽,如果有,則在適當的位置使用view.performClick()觸發點擊事件。