ButterKnife's OnClick侦听器出现一个奇怪的问题。在下面打开我的自定义视图时,打开视图时,OnClick侦听器将自动运行。以下代码可帮助您了解我的问题。
$args = array(
'post_type'=> 'products',
'posts_per_page' => 4,
'meta_key' => 'focus_product',
'meta_value' => 1
);
}
IMO之所以发生这种情况,是因为我在构造函数中调用了OnClick侦听器,因此在视图创建(创建后)时自然会在运行它们。有人可以帮助我了解确切的问题在哪里以及如何解决吗?
我的ButterKnife版本:
public class UserMenuFragment extends LinearLayout {
@BindView(R.id.buttonBlockUser)
Button buttonBlockUser;
@BindView(R.id.buttonMuteUser)
Button buttonMuteUser;
@BindView(R.id.buttonHideYourPreset)
Button buttonHideYourPreset;
@BindView(R.id.buttonTurnOnNotifs)
Button buttonTurnOnNotifs;
public UserMenuFragment(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initView();
}
public UserMenuFragment(Context context, AttributeSet attrs) {
super(context, attrs);
initView();
}
public UserMenuFragment(Context context) {
super(context);
initView();
}
private void initView() {
View view = inflate(getContext(), R.layout.fragment_user_menu, null);
addView(view);
bindViewWithButterKnife(this, view);
onButtonReportUserClicked();
onButtonBlockUserClicked();
onButtonMuteUserClicked();
onButtonHideYourPresetClicked();
onButtonCopyProfileLinkClicked();
onButtonTurnOnNotifsClicked();
}
@OnClick(R.id.buttonReportUser)
void onButtonReportUserClicked() {
Toast.makeText(getContext(), "User Reported!", Toast.LENGTH_SHORT).show();
}
@OnClick(R.id.buttonBlockUser)
void onButtonBlockUserClicked() {
Toast.makeText(getContext(), "User Blocked!", Toast.LENGTH_SHORT).show();
changeButtonText(buttonBlockUser, R.string.unblock_user_text);
}
@OnClick(R.id.buttonMuteUser)
void onButtonMuteUserClicked() {
Toast.makeText(getContext(), "User Muted!", Toast.LENGTH_SHORT).show();
changeButtonText(buttonMuteUser, R.string.unmute_user_text);
}
@OnClick(R.id.buttonHideYourPreset)
void onButtonHideYourPresetClicked() {
Toast.makeText(getContext(), "User preset hided!", Toast.LENGTH_SHORT).show();
buttonHideYourPreset.setText(getContext().getString(R.string.show_your_preset_text));
changeButtonText(buttonHideYourPreset, R.string.show_your_preset_text);
}
@OnClick(R.id.buttonCopyProfileLink)
void onButtonCopyProfileLinkClicked() {
Toast.makeText(getContext(), "User's profile link copied!", Toast.LENGTH_SHORT).show();
}
@OnClick(R.id.buttonTurnOnNotifs)
void onButtonTurnOnNotifsClicked() {
Toast.makeText(getContext(), "User's notification is off now!!", Toast.LENGTH_SHORT).show();
changeButtonText(buttonTurnOnNotifs, R.string.turn_off_notification_text);
}
private void changeButtonText(Button button, int newText) {
button.setText(getContext().getString(newText));
}
private void bindViewWithButterKnife(UserMenuFragment whichFragment, View view) {
ButterKnife.bind(whichFragment, view);
}
答案 0 :(得分:1)
将initView()
更改为:
private void initView() {
View view = inflate(getContext(), R.layout.fragment_user_menu, null);
addView(view);
bindViewWithButterKnife(this, view);
}
我认为您不需要调用方法,注释已经可以完成设置侦听器的工作了,对吧?