Android OnLongClickListener strange / unreliable b

2020-03-26 08:16发布

问题:

I'm currently fighting against the OnLongClickListener on Android Api Lvl 8.

Take this code:

this.webView.setOnLongClickListener(new OnLongClickListener() {
    @Override
    public boolean onLongClick(View v) {
        System.out.println("long click");
        return true;
    }
});

It works perfectly. I can press anywhere on the WebView and the event triggers every time.

Now take a look at this one:

this.webView.setOnLongClickListener(new OnLongClickListener() {
    @Override
    public boolean onLongClick(View v) {
        final EditText editText = getUrlTextField();

        switch (editText.getVisibility()) {
        case View.VISIBLE:
            editText.setVisibility(View.GONE);
            return true;
        case View.GONE:
            editText.setVisibility(View.VISIBLE);
            return true;
        default:
            return false;
        }
    }
});

Assuming the URL EditText components is currently visible, it gets gone from the display and should be shown again when another long click event is triggered. But if you run this, the event just works once (!) when one performs a long click on any position on the WebView. To make things complicated, the long click works again when it is performed on a link on the website...

Can anyone explain if it is a bug in the sdk and/or if there is a mistake in my thinking how the OnLongClickListener is working?!? :/

EDIT:

I've run now several different scenarios on a Nexus One and come to following conclussion: Changing the layout on runtime more or less kills the OnLongClickListener... I haven't found a way to get it work reliably at all...

I would really appreciate if anyone could give me a hint... I'm at my wits end :(

回答1:

Personnally, I ended up by re-setting the listener after each relayout.



回答2:

I've run into this issue as well. It seems that if the view layout changes in a way that child view bounds need to be modified (i.e. TextView is wrap_content width and you set its text to something longer/shorter than it was before), views in the hierarchy will have their onStartTemporaryDetach method called (most likely due to a layout pass, although I haven't dug deep enough to find out for sure). If you look at the source for View that onStartTemporaryDetach ultimately unsets the pressed state of the view.

Changing the views in your layout that will be updated periodically to have bounds that will not change regardless of the value you set, will fix the issue. Although, that is still not awesome.