Home | History | Annotate | Download | only in common
      1 /*
      2  * Copyright 2017, The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 package com.android.managedprovisioning.common;
     17 
     18 import android.content.res.Resources;
     19 
     20 import com.android.managedprovisioning.R;
     21 
     22 import java.util.List;
     23 
     24 /**
     25  * Concatenates {@link String}s in an i18n safe way.
     26  * <p>
     27  * Based on the implementation from <a href="https://android.googlesource.com/platform/packages/apps/Settings/+/2d566e7/src/com/android/settings/applications/AppPermissionSettings.java#136">com.android.settings.applications.AppPermissionSettings</a>
     28  */
     29 public class StringConcatenator {
     30     private final Resources mResources;
     31 
     32     public StringConcatenator(Resources resources) {
     33         mResources = resources;
     34     }
     35 
     36     public String join(List<String> items) {
     37         if (items == null) {
     38             return null;
     39         }
     40 
     41         if (items.isEmpty()) {
     42             return "";
     43         }
     44 
     45         final int count = items.size();
     46 
     47         if (count == 1) {
     48             return items.get(0);
     49         }
     50 
     51         if (count == 2) {
     52             return mResources.getString(R.string.join_two_items, items.get(0), items.get(1));
     53         }
     54 
     55         String result = items.get(count - 2);
     56         for (int i = count - 3; i >= 0; i--) {
     57             result = mResources.getString( // not the fastest, but good enough
     58                     i == 0 ? R.string.join_many_items_first : R.string.join_many_items_middle,
     59                     items.get(i), result);
     60         }
     61         result = mResources.getString(R.string.join_many_items_last, result, items.get(count - 1));
     62         return result;
     63     }
     64 }