onClickListener vs onClick()

时间:2016-02-04 09:36:21

标签: android onclick onclicklistener android-xml

如果我们从xml调用onClickListeneronClick()方法,则始终调用onClickListener方法。
为什么会这样?

public class MainActivity extends Activity {
Button buttonCheck;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    buttonCheck = (Button) findViewById(R.id.buttonTesting);
    buttonCheck.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(getApplicationContext(), "On Click Listener", Toast.LENGTH_SHORT).show();
            Log.e("OnClick", "Called");
        }
    });
}
public void checkStatus(View view) {
    Toast.makeText(getApplicationContext(), "On checkStatus", Toast.LENGTH_SHORT).show();
    Log.e("checkStatus", "Called");
}

}

xml layout:

    <Button
    android:id="@+id/buttonTesting"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="162dp"
    android:onClick="checkStatus"
    android:text="Check" />

2 个答案:

答案 0 :(得分:8)

onClick中的{p> xml在创建视图时只调用setOnClickListener。当您在代码中调用setOnClickListener时,它会覆盖OnClickListener中设置的现有xml

答案 1 :(得分:0)

因为当调用Button类构造函数从xml进行膨胀时,它会将onClick方法设置为checkStatus。 现在你在你的活动onCreate中覆盖了这个。 因此,后一个是onClick,它将被getCalled。