summaryrefslogtreecommitdiff
path: root/src/com/android/car/dialer/ContactSearchActivity.java
blob: cb2e43df2839c88ded92072608402f6151cf05f6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
/*
 * Copyright (C) 2017 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.car.dialer;

import android.animation.ValueAnimator;
import android.app.Activity;
import android.app.Fragment;
import android.app.SearchManager;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;

import com.android.car.view.CarLayoutManager;

/**
 * An activity that manages contact searching. This activity will display the result of a search
 * as well as show the details of a contact when that contact is clicked.
 */
public class ContactSearchActivity extends Activity {
    private static final String CONTENT_FRAGMENT_TAG = "CONTENT_FRAGMENT_TAG";
    private static final int ANIMATION_DURATION_MS = 100;

    /**
     * A delay before actually starting a contact search. This ensures that there are not too many
     * queries happening when the user is still typing.
     */
    private static final int CONTACT_SEARCH_DELAY = 400;

    private final Handler mHandler = new Handler();
    private Runnable mCurrentSearch;

    private View mSearchContainer;
    private EditText mSearchField;

    private float mContainerElevation;
    private ValueAnimator mRemoveElevationAnimator;

    /**
     * Whether or not it is safe to make transactions on the {@link android.app.FragmentManager}.
     * This variable prevents a possible exception when calling commit() on the FragmentManager.
     *
     * <p>The default value is {@code true} because it is only after
     * {@link #onSaveInstanceState(Bundle)} that fragment commits are not allowed.
     */
    private boolean mAllowFragmentCommits = true;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.contact_search_activity);

        mSearchContainer = findViewById(R.id.search_container);
        mSearchField = findViewById(R.id.search_field);

        mSearchField.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}

            @Override
            public void afterTextChanged(Editable s) {
                if (!(getCurrentFragment() instanceof ContactResultsFragment)) {
                    showContactResultList(s.toString());
                    return;
                }

                // Cancel any pending searches.
                if (mCurrentSearch != null) {
                    mHandler.removeCallbacks(mCurrentSearch);
                }

                // Queue up a new search. This will be cancelled if the user types within the
                // time frame specified by CONTACT_SEARCH_DELAY.
                mCurrentSearch = new SearchRunnable(s.toString());
                mHandler.postDelayed(mCurrentSearch, CONTACT_SEARCH_DELAY);
            }
        });

        mContainerElevation = getResources()
                .getDimension(R.dimen.search_container_elevation);

        mRemoveElevationAnimator = ValueAnimator.ofFloat(mContainerElevation, 0.f);
        mRemoveElevationAnimator
                .setDuration(ANIMATION_DURATION_MS)
                .addUpdateListener(animation -> mSearchContainer.setElevation(
                        (float) animation.getAnimatedValue()));

        findViewById(R.id.back).setOnClickListener(v -> finish());
        findViewById(R.id.clear).setOnClickListener(v -> {
            mSearchField.getText().clear();

            Fragment currentFragment = getCurrentFragment();
            if (currentFragment instanceof ContactResultsFragment) {
                ((ContactResultsFragment) currentFragment).clearResults();
            }
        });

        handleIntent(getIntent());
    }

    @Override
    protected void onNewIntent(Intent intent) {
        setIntent(intent);
        handleIntent(intent);
    }

    /**
     * Inspects the Action within the given intent and loads up the appropriate fragment based on
     * this.
     */
    private void handleIntent(Intent intent) {
        if (intent == null || intent.getAction() == null) {
            showContactResultList(null /* query */);
            return;
        }

        switch (intent.getAction()) {
            case Intent.ACTION_SEARCH:
                showContactResultList(intent.getStringExtra(SearchManager.QUERY));
                break;

            case TelecomIntents.ACTION_SHOW_CONTACT_DETAILS:
                Uri contactUri = Uri.parse(intent.getStringExtra(
                        TelecomIntents.CONTACT_LOOKUP_URI_EXTRA));
                setContentFragment(ContactDetailsFragment.newInstance(contactUri,
                        new ContactScrollListener()));
                break;

            default:
                showContactResultList(null /* query */);
        }
    }

    /**
     * Displays the fragment that will show the results of a search. The given query is used as
     * the initial search to populate the list.
     */
    private void showContactResultList(@Nullable String query) {
        // Check that the result list is not already being displayed. If it is, then simply set the
        // search query.
        Fragment currentFragment = getCurrentFragment();
        if (currentFragment instanceof ContactResultsFragment) {
            ((ContactResultsFragment) currentFragment).setSearchQuery(query);
            return;
        }

        setContentFragment(ContactResultsFragment.newInstance(new ContactScrollListener(), query));
    }

    /**
     * Sets the fragment that will be shown as the main content of this Activity.
     */
    private void setContentFragment(Fragment fragment) {
        if (!mAllowFragmentCommits) {
            return;
        }

        // The search panel might have elevation added to it, so remove it when the fragment
        // changes since any lists in it will be reset to the top.
        resetSearchPanelElevation();

        getFragmentManager().beginTransaction()
                .setCustomAnimations(R.animator.fade_in, R.animator.fade_out)
                .replace(R.id.content_fragment_container, fragment, CONTENT_FRAGMENT_TAG)
                .commitNow();
    }

    /**
     * Returns the fragment that is currently being displayed as the content view.
     */
    @Nullable
    private Fragment getCurrentFragment() {
        return getFragmentManager().findFragmentByTag(CONTENT_FRAGMENT_TAG);
    }

    @Override
    protected void onStart() {
        super.onStart();
        // Fragment commits are not allowed once the Activity's state has been saved. Once
        // onStart() has been called, the FragmentManager should now allow commits.
        mAllowFragmentCommits = true;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        // A transaction can only be committed with this method prior to its containing activity
        // saving its state.
        mAllowFragmentCommits = false;
        super.onSaveInstanceState(outState);
    }

    /**
     * Checks if {@link #mSearchContainer} has an elevation set on it and if it does, animates the
     * removal of this elevation.
     */
    private void resetSearchPanelElevation() {
        if (mSearchContainer.getElevation() != 0.f) {
            mRemoveElevationAnimator.start();
        }
    }

    /**
     * A {@link Runnable} that will execute a contact search with the given {@link #mSearchQuery}.
     */
    private class SearchRunnable implements Runnable {
        private final String mSearchQuery;

        public SearchRunnable(String searchQuery) {
            mSearchQuery = searchQuery;
        }

        @Override
        public void run() {
            Fragment currentFragment = getCurrentFragment();
            if (currentFragment instanceof ContactResultsFragment) {
                ((ContactResultsFragment) currentFragment).setSearchQuery(mSearchQuery);
            }
        }
    }

    /**
     * Listener for scrolls in a fragment that has a list. It will will add elevation on the
     * container holding the search field. This elevation will give the illusion of the list
     * scrolling under that container.
     */
    public class ContactScrollListener extends RecyclerView.OnScrollListener {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            // Assuming CarLayoutManager is the layout manager as all car applications should be
            // using a PagedListView.
            CarLayoutManager layoutManager = (CarLayoutManager) recyclerView.getLayoutManager();

            if (layoutManager.isAtTop()) {
                resetSearchPanelElevation();
            } else {
                // No animation needed when adding the elevation because the scroll masks the adding
                // of the elevation.
                mSearchContainer.setElevation(mContainerElevation);
            }
        }
    }
}