View的 setClickable() 和 setEnabled()

1. setClickable

/**
 * Enables or disables click events for this view. When a view
 * is clickable it will change its state to "pressed" on every click.
 * Subclasses should set the view clickable to visually react to
 * user's clicks.
 *
 * @param clickable true to make the view clickable, false otherwise
 *
 * @see #isClickable()
 * @attr ref android.R.styleable#View_clickable
 */
public void setClickable(boolean clickable) {
	setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
}

源碼如上,當爲false之後,控件不可點擊是會往下面繼續傳遞的。

但是,有個主要注意的,clickable設置點擊事件之後,會變成true,如果需要取消點擊事件則需要在設置完點擊事件之後在設置爲false。

/**
 * Register a callback to be invoked when this view is clicked. If this view is not
 * clickable, it becomes clickable.
 *
 * @param l The callback that will run
 *
 * @see #setClickable(boolean)
 */
public void setOnClickListener(@Nullable OnClickListener l) {
	if (!isClickable()) {
		setClickable(true);
	}
	getListenerInfo().mOnClickListener = l;
}

2. setEnabled()

/**
 * Set the enabled state of this view. The interpretation of the enabled
 * state varies by subclass.
 *
 * @param enabled True if this view is enabled, false otherwise.
 */
@RemotableViewMethod
public void setEnabled(boolean enabled) {
	if (enabled == isEnabled()) return;

	setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);

	/*
	 * The View most likely has to change its appearance, so refresh
	 * the drawable state.
	 */
	refreshDrawableState();

	// Invalidate too, since the default behavior for views is to be
	// be drawn at 50% alpha rather than to change the drawable.
	invalidate(true);

	if (!enabled) {
		cancelPendingInputEvents();
	}
}

enabled與clickable的關係不大,當enabled設置爲false之後按鈕則不可點擊,假如clickable設置爲true消耗了點擊事件,則事件不會在繼續向下傳遞。

3. 總結

如果控件設置不可點擊之後,想讓底層的按鈕可以點擊使用clickable,反則用enabled。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章