Анимация onLongClick с AsyncTask

Я хотел бы начать анимацию при длительном щелчке по просмотру.

Код выглядит следующим образом.

public class Example_Dialog extends Dialog implements AnimationListener{
    TextView    view_Description1 = null;
    View        view_Button1 = null;
    MessageCreateTask task;

    public Example_Dialog( Context context , int theme ){
        super( context , theme );

        setContentView(R.layout.infomation_dialog);

        view_Button1 = findViewById(R.id.common_dialog_button_1);
        view_Description1 = (TextView)findViewById(R.id.common_dialog_description_1);
        view_Description1.setHeight(0);

        view_Button1.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v){
                task = new MessageCreateTask(view_Description1);
                task.execute();
            }
        });
    }

    @Override
    public void onAnimationEnd(Animation animation) {
    }

    @Override
    public void onAnimationRepeat(Animation animation) {
    }

    @Override
    public void onAnimationStart(Animation animation) {
    }


    class MessageCreateTask extends AsyncTask<Void, Void, String> {
        TextView textView;

        String messageOutput;
        int totalLineNum;

        public MessageCreateTask(TextView textView) {
            this.textView = textView;

            messageOutput = "";
            totalLineNum = 0;
        }

        @Override
          protected void onPreExecute() {
        }

        @Override
        protected String doInBackground(Void... params) {
            for( int i= 0 ; i< 10 ; i++ ){
                messageOutput += "a" + "<br>";
                totalLineNum++;
            }
            return messageOutput;
        }

        @Override
        protected void onPostExecute(String message) {
            int dialogWidth     = 838;
            int dialogHeight    = 26*totalLineNum;

            textView.setWidth( dialogWidth );
            textView.setText(Html.fromHtml(message));

            HeightAnimation hanime_open = new HeightAnimation(textView , 0 , dialogHeight );
            hanime_open = new HeightAnimation(textView , 0 , dialogHeight );
            hanime_open.setDuration(300);

            textView.startAnimation(hanime_open);
        }
    }
}


public class HeightAnimation extends Animation {

    int targetHeight;
    int startHeight;
    TextView textView;

    public HeightAnimation(TextView textView,int startHeight, int targetHeight) {
        this.textView = textView;
        this.targetHeight = targetHeight;
        this.startHeight = startHeight;
    }

    @Override
    protected void applyTransformation(float interpolatedTime, Transformation t) {
        int newHeight = (int)(startHeight + (targetHeight - startHeight)*interpolatedTime);
        textView.setHeight(newHeight);

        if( (startHeight != 0) && (newHeight == 0) ){
            textView.setVisibility(View.GONE);
        }
    }

    @Override
    public void initialize(int width, int height, int parentWidth, int parentHeight) {
        super.initialize(width, height, ((View)textView.getParent()).getWidth(), parentHeight);
    }
}


Анимация не была запущена с помощью приведенного выше кода, но она была запущена путем замены onclick на onlongclick, как показано ниже.


        view_Button1.setOnLongClickListener(new View.OnLongClickListener(){
            public boolean onLongClick(View v){
                task = new MessageCreateTask(view_Description1);
                task.execute();

                return true;
            }
        });


Я хочу знать причину, по которой анимация не запускается при клике.


person fuji    schedule 29.05.2017    source источник
comment
это всего лишь предположение, может это как-то связано с фокусом. Я предполагаю, что фокус не на этом взгляде. Работает ли это с onClickListener(), если вы дважды нажмете кнопку?   -  person Opiatefuchs    schedule 29.05.2017
comment
да. Если я дважды нажимаю кнопку (двойное нажатие), она работает с onClickListener.   -  person fuji    schedule 29.05.2017
comment
Тогда это проблема с фокусом. Может быть, это сработает, если вы позвоните view_button1.requestFocus() после setHeight()   -  person Opiatefuchs    schedule 29.05.2017
comment
Спасибо за совет. Я вызвал requestFocus перед запуском анимации, но ничего не изменилось.   -  person fuji    schedule 29.05.2017
comment
Вы установили в своем макете XML: android:focusableInTouchMode="true"? или сделайте это программно перед вызовом requestFocus() : view_button1.setFocusableInTouchMode(true);   -  person Opiatefuchs    schedule 29.05.2017
comment
Спасибо за чудесный совет!! После установки setFocusableInTouchMode(true) он получил ожидаемое поведение!!   -  person fuji    schedule 29.05.2017
comment
отлично, я положил ответ здесь ...   -  person Opiatefuchs    schedule 29.05.2017
comment
Это спецификация андроида, что фокус теряется в лонгклике??   -  person fuji    schedule 29.05.2017
comment
фокус зависит от пользовательского ввода, как на веб-сайте. Но это редко документируется внутри API, какое представление и почему это представление принимает или не принимает фокус и в какой ситуации это происходит. Это действительно сложно...   -  person Opiatefuchs    schedule 29.05.2017
comment
Я понимаю. понял.   -  person fuji    schedule 30.05.2017


Ответы (1)


Причина, по которой он не работает с onClickListener(), заключается в том, что у view нет Фокуса. Так что вам нужно нажать кнопку дважды или вы должны использовать onlongClickListener(). Чтобы сделать view clickable в первый раз, сделайте следующее:

включить фокусировку в сенсорном режиме, будь то в вашем XML-макете как атрибут:

android:focusableInTouchMode="true"

или программно после инициализации кнопки:

view_button1.setFocusableInTouchMode(true);

Затем вы можете просто установить фокус на представление:

view_button1.requestFocus();
person Opiatefuchs    schedule 29.05.2017