Example usage for android.widget GridLayout spec

List of usage examples for android.widget GridLayout spec

Introduction

In this page you can find the example usage for android.widget GridLayout spec.

Prototype

public static Spec spec(int start, int size) 

Source Link

Document

Return a Spec, spec , where:
  • spec.span = [start, start + size]

To leave the start index undefined, use the value #UNDEFINED .

Usage

From source file:com.softminds.matrixcalculator.base_fragments.ViewMatrixFragment.java

@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    int index = getArguments().getInt("INDEX");

    View v = inflater.inflate(R.layout.view_matrix_frag, container, false);
    CardView cardView = v.findViewById(R.id.DynamicCardView);

    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
    String string = sharedPreferences.getString("ELEVATE_AMOUNT", "4");
    String string2 = sharedPreferences.getString("CARD_CHANGE_KEY", "#bdbdbd");

    cardView.setCardElevation(Integer.parseInt(string));

    final int border = getResources().getDimensionPixelOffset(R.dimen.border_width);

    CardView.LayoutParams params1 = new CardView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT);
    cardView.setUseCompatPadding(true);/*from w ww  .  j  a v  a  2s  .  com*/

    GridLayout gridLayout = new GridLayout(getContext());
    int rows = ((GlobalValues) getActivity().getApplication()).GetCompleteList().get(index).getNumberOfRows();
    int cols = ((GlobalValues) getActivity().getApplication()).GetCompleteList().get(index).getNumberOfCols();

    gridLayout.setRowCount(rows);
    gridLayout.setColumnCount(cols);
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            TextView textView = new TextView(getContext());
            textView.setGravity(Gravity.CENTER);
            textView.setBackgroundColor(Color.parseColor(string2));
            textView.setText(SafeSubString(GetText(((GlobalValues) getActivity().getApplication())
                    .GetCompleteList().get(index).getElementOf(i, j)), getLength()));
            textView.setWidth(CalculatedWidth(cols));
            textView.setTextSize(SizeReturner(rows, cols, PreferenceManager
                    .getDefaultSharedPreferences(getContext()).getBoolean("EXTRA_SMALL_FONT", false)));
            textView.setHeight(CalculatedHeight(rows));
            GridLayout.Spec Row = GridLayout.spec(i, 1);
            GridLayout.Spec Col = GridLayout.spec(j, 1);
            GridLayout.LayoutParams params = new GridLayout.LayoutParams(Row, Col);
            params.leftMargin = params.topMargin = params.bottomMargin = params.rightMargin = border;
            gridLayout.addView(textView, params);
        }
    }
    gridLayout.setLayoutParams(params1);
    cardView.addView(gridLayout);

    // Inflate the layout for this fragment
    return v;
}

From source file:com.softminds.matrixcalculator.base_fragments.EditFragment.java

@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View V = inflater.inflate(R.layout.fragment_edit, container, false);

    CardView cardView = V.findViewById(R.id.EditMatrixCard);

    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
    String string = sharedPreferences.getString("ELEVATE_AMOUNT", "4");
    String string2 = sharedPreferences.getString("CARD_CHANGE_KEY", "#bdbdbd");

    cardView.setCardElevation(Integer.parseInt(string));

    CardView.LayoutParams params1 = new CardView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT);

    //noinspection ConstantConditions
    int index = getArguments().getInt("INDEX");
    //noinspection ConstantConditions
    MatrixV2 m = ((GlobalValues) getActivity().getApplication()).GetCompleteList().get(index);

    GridLayout gridLayout = new GridLayout(getContext());
    gridLayout.setRowCount(m.getNumberOfRows());
    gridLayout.setColumnCount(m.getNumberOfCols());
    for (int i = 0; i < m.getNumberOfRows(); i++) {
        for (int j = 0; j < m.getNumberOfCols(); j++) {
            EditText editText = new EditText(getContext());
            editText.setId(i * 10 + j);//from  ww w  . jav a 2  s . com
            editText.setBackgroundColor(Color.parseColor(string2));
            editText.setGravity(Gravity.CENTER);
            if (!PreferenceManager.getDefaultSharedPreferences(getContext()).getBoolean("DECIMAL_USE", true)) {
                editText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED);
            } else {
                editText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL
                        | InputType.TYPE_NUMBER_FLAG_SIGNED);
            }
            editText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(getLength()) });
            if (!PreferenceManager.getDefaultSharedPreferences(getContext()).getBoolean("SMART_FIT_KEY",
                    false)) {
                editText.setWidth(ConvertTopx(62));
                editText.setTextSize(SizeReturner(3, 3, PreferenceManager
                        .getDefaultSharedPreferences(getContext()).getBoolean("EXTRA_SMALL_FONT", false)));
            } else {
                editText.setWidth(ConvertTopx(CalculatedWidth(m.getNumberOfCols())));
                editText.setTextSize(SizeReturner(m.getNumberOfRows(), m.getNumberOfCols(), PreferenceManager
                        .getDefaultSharedPreferences(getContext()).getBoolean("EXTRA_SMALL_FONT", false)));
            }
            editText.setText(SafeSubString(GetText(m.getElementOf(i, j)), getLength()));
            editText.setSingleLine();
            GridLayout.Spec Row = GridLayout.spec(i, 1);
            GridLayout.Spec Col = GridLayout.spec(j, 1);
            GridLayout.LayoutParams params = new GridLayout.LayoutParams(Row, Col);
            params.leftMargin = params.topMargin = params.bottomMargin = params.rightMargin = getResources()
                    .getDimensionPixelOffset(R.dimen.border_width);
            gridLayout.addView(editText, params);
        }
    }
    gridLayout.setLayoutParams(params1);
    cardView.addView(gridLayout);
    RootView = V;
    return V;
}

From source file:com.softminds.matrixcalculator.base_activities.FillingMatrix.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    boolean isDark = preferences.getBoolean("DARK_THEME_KEY", false);
    boolean SmartFit = preferences.getBoolean("SMART_FIT_KEY", false);

    if (isDark)/*from w  w  w .j  a v a2 s.c  o m*/
        setTheme(R.style.AppThemeDark_NoActionBar);
    else
        setTheme(R.style.AppTheme_NoActionBar);
    super.onCreate(savedInstanceState);

    Bundle bundle = getIntent().getExtras();
    if (bundle == null) {
        Log.wtf("FillingMatrix", "How the heck, it got called ??");
        Toast.makeText(getApplication(), R.string.unexpected_error, Toast.LENGTH_SHORT).show();
        finish();
    } else {
        col = bundle.getInt("COL");
        row = bundle.getInt("ROW");
    }
    setContentView(R.layout.filler);
    adCard = findViewById(R.id.AddCardFiller);

    if (!((GlobalValues) getApplication()).DonationKeyFound()) {
        AdView adView = findViewById(R.id.adViewFiller);
        AdRequest adRequest = new AdRequest.Builder().build();
        adView.setAdListener(new AdLoadListener(adCard));
        adView.loadAd(adRequest);
        if (getResources()
                .getConfiguration().orientation == android.content.res.Configuration.ORIENTATION_LANDSCAPE)
            adCard.setVisibility(View.INVISIBLE);
        else
            adCard.setVisibility(View.VISIBLE);
    } else
        ((ViewGroup) adCard.getParent()).removeView(adCard);

    Toolbar toolbar = findViewById(R.id.toolbarFill);
    setSupportActionBar(toolbar);

    CardView cardView = findViewById(R.id.DynamicCard);

    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    String string = sharedPreferences.getString("ELEVATE_AMOUNT", "4");
    String string2 = sharedPreferences.getString("CARD_CHANGE_KEY", "#bdbdbd");

    cardView.setCardElevation(Integer.parseInt(string));

    CardView.LayoutParams params1 = new CardView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT);

    GridLayout gridLayout = new GridLayout(getApplicationContext());
    gridLayout.setRowCount(row);
    gridLayout.setColumnCount(col);
    for (int i = 0; i < row; i++) {
        for (int j = 0; j < col; j++) {
            EditText editText = new EditText(getApplication());
            editText.setBackgroundColor(Color.parseColor(string2));
            editText.setId(i * 10 + j);
            if (isDark)
                editText.setTextColor(ContextCompat.getColor(this, R.color.white));
            editText.setGravity(Gravity.CENTER);
            SpannableStringBuilder stringBuilder = new SpannableStringBuilder(
                    "a" + String.valueOf(i + 1) + String.valueOf(j + 1));
            stringBuilder.setSpan(new SubscriptSpan(), 1, 3, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            stringBuilder.setSpan(new RelativeSizeSpan(0.75f), 1, 3, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            editText.setHint(stringBuilder);
            if (!PreferenceManager.getDefaultSharedPreferences(this).getBoolean("DECIMAL_USE", true)) {
                editText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED);
            } else {
                editText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL
                        | InputType.TYPE_NUMBER_FLAG_SIGNED);
            }
            editText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(getLength()) });
            if (SmartFit) {
                editText.setWidth(ConvertTopx(CalculatedWidth(col)));
                editText.setTextSize(SizeReturner(row, col,
                        PreferenceManager.getDefaultSharedPreferences(getApplicationContext())
                                .getBoolean("EXTRA_SMALL_FONT", false)));
            } else {
                editText.setWidth(ConvertTopx(62));
                editText.setTextSize(SizeReturner(3, 3,
                        PreferenceManager.getDefaultSharedPreferences(getApplicationContext())
                                .getBoolean("EXTRA_SMALL_FONT", false)));
            }
            editText.setSingleLine();
            GridLayout.Spec Row = GridLayout.spec(i, 1);
            GridLayout.Spec Col = GridLayout.spec(j, 1);
            GridLayout.LayoutParams params = new GridLayout.LayoutParams(Row, Col);
            params.leftMargin = params.topMargin = params.bottomMargin = params.rightMargin = getResources()
                    .getDimensionPixelOffset(R.dimen.border_width);
            gridLayout.addView(editText, params);
        }
    }
    gridLayout.setLayoutParams(params1);
    cardView.addView(gridLayout);
    MakeType((Type) (getIntent().getExtras().getSerializable("TYPE")));
    if (GetMaximum() < GetMinimum()) {
        final Snackbar snackbar;
        snackbar = Snackbar.make(findViewById(R.id.filling_matrix), R.string.Warning3,
                Snackbar.LENGTH_INDEFINITE);
        snackbar.show();
        snackbar.setAction(getString(R.string.action_settings), new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                snackbar.dismiss();
                Intent intent = new Intent(getApplicationContext(), SettingsTab.class);
                startActivity(intent);
                finish();
            }
        });
    }

}

From source file:nz.ac.otago.psyanlab.common.designer.program.stage.EditPropPropertiesFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    Bundle args = getArguments();/* www. j  a  va2  s  .c  om*/
    if (args.containsKey(ARG_PROP)) {
        mProp = args.getParcelable(ARG_PROP);
    } else {
        mProp = mCallbacks.getProp(args.getInt(ARG_PROP_ID)).getProp();
    }

    mFieldMap = new HashMap<String, Field>();
    mViewMap = new HashMap<String, View>();

    // Run through the fields of the prop and build groups and mappings for
    // the fields and views to allow the user to change the property values.
    Field[] fields = mProp.getClass().getFields();
    for (int i = 0; i < fields.length; i++) {
        Field field = fields[i];
        PALEPropProperty annotation = field.getAnnotation(PALEPropProperty.class);
        if (annotation != null) {
            String fieldName = annotation.value();
            View view;
            if (field.getType().isAssignableFrom(Integer.TYPE)) {
                try {
                    view = newIntegerInputView(annotation.isSigned(), field.getInt(mProp));
                } catch (IllegalArgumentException e) {
                    throw new RuntimeException("Should never get here.", e);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException("Should never get here.", e);
                }
            } else if (field.getType().isAssignableFrom(Float.TYPE)) {
                try {
                    view = newFloatInputView(annotation.isSigned(), field.getFloat(mProp));
                } catch (IllegalArgumentException e) {
                    throw new RuntimeException("Should never get here.", e);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException("Should never get here.", e);
                }
            } else if (field.getType().isAssignableFrom(String.class)) {
                try {
                    view = newStringInputView((String) field.get(mProp));
                } catch (IllegalArgumentException e) {
                    throw new RuntimeException("Should never get here.", e);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException("Should never get here.", e);
                }
            } else {
                continue;
            }
            mFieldMap.put(fieldName, field);
            mViewMap.put(fieldName, view);

            if (mGroupings.containsKey(annotation.group())) {
                mGroupings.get(annotation.group()).add(fieldName);
            } else {
                ArrayList<String> list = new ArrayList<String>();
                list.add(fieldName);
                mGroupings.put(annotation.group(), list);
            }
        }
    }

    // Initialise grid layout.
    GridLayout grid = new GridLayout(getActivity());
    grid.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT));
    grid.setAlignmentMode(GridLayout.ALIGN_BOUNDS);
    grid.setColumnCount(2);
    grid.setUseDefaultMargins(true);

    // Run through groupings of properties adding the created views to the
    // GridLayout in sections.
    for (String group : mGroupings.keySet()) {
        if (!TextUtils.isEmpty(group) && !TextUtils.equals(group, "")) {
            TextView sectionBreak = (TextView) inflater.inflate(R.layout.prop_property_section_break, grid,
                    false);
            sectionBreak.setText(group);
            GridLayout.LayoutParams sectionBreakParams = new GridLayout.LayoutParams();
            sectionBreakParams.columnSpec = GridLayout.spec(0, 2);
            sectionBreak.setLayoutParams(sectionBreakParams);
            grid.addView(sectionBreak);
        }

        for (String name : mGroupings.get(group)) {
            TextView propertyLabel = (TextView) inflater.inflate(R.layout.prop_property_label, grid, false);
            GridLayout.LayoutParams params = new GridLayout.LayoutParams();
            propertyLabel.setLayoutParams(params);
            propertyLabel.setText(getResources().getString(R.string.format_property_label, name));

            View propertyView = mViewMap.get(name);
            params = new GridLayout.LayoutParams();
            params.setGravity(Gravity.FILL_HORIZONTAL);
            propertyView.setLayoutParams(params);

            grid.addView(propertyLabel);
            grid.addView(propertyView);
        }
    }

    return grid;
}

From source file:ch.epfl.sweng.evento.tabs_fragment.ContentFragment.java

public void addViewToGridLayout(View view, int row, int column, int rowSpan, int columnSpan, int width) {
    GridLayout.LayoutParams params = new GridLayout.LayoutParams();
    params.width = width + 2 * PADDING;//from   w w  w . j a v a 2 s . c  o m
    params.setMargins(PADDING, PADDING, PADDING, PADDING);
    params.columnSpec = GridLayout.spec(column, columnSpan);
    params.rowSpec = GridLayout.spec(row, rowSpan);

    mGridLayout.addView(view, params);
}

From source file:com.affectiva.affdexme.MetricSelectionFragment.java

void addHeader(String name, IntRef currentRow, int numColumns, LayoutInflater inflater) {

    View header = inflater.inflate(R.layout.grid_header, null);

    //each header should take up one row and all available columns
    GridLayout.LayoutParams params = new GridLayout.LayoutParams(GridLayout.spec(currentRow.value, 1),
            GridLayout.spec(0, numColumns));
    params.width = gridLayout.getWidth();
    header.setLayoutParams(params);//ww w  .  jav  a 2s  . com
    gridLayout.addView(header);

    ((TextView) header.findViewById(R.id.header_text)).setText(name);

    currentRow.value += 1; //point currentRow to row where next views should be added
}

From source file:com.phonemetra.turbo.launcher.AsyncTaskCallback.java

public void syncWidgetPageItems(final int page, final boolean immediate) {
    int numItemsPerPage = mWidgetCountX * mWidgetCountY;

    // Calculate the dimensions of each cell we are giving to each widget
    final ArrayList<Object> items = new ArrayList<Object>();
    int contentWidth = mContentWidth;
    final int cellWidth = ((contentWidth - mPageLayoutPaddingLeft - mPageLayoutPaddingRight
            - ((mWidgetCountX - 1) * mWidgetWidthGap)) / mWidgetCountX);
    int contentHeight = mContentHeight;
    final int cellHeight = ((contentHeight - mPageLayoutPaddingTop - mPageLayoutPaddingBottom
            - ((mWidgetCountY - 1) * mWidgetHeightGap)) / mWidgetCountY);

    // Prepare the set of widgets to load previews for in the background
    int offset = page * numItemsPerPage;
    for (int i = offset; i < Math.min(offset + numItemsPerPage, mFilteredWidgets.size()); ++i) {
        items.add(mFilteredWidgets.get(i));
    }// w w  w. ja  v  a2  s  . co m

    // Prepopulate the pages with the other widget info, and fill in the previews later
    final PagedViewGridLayout layout = (PagedViewGridLayout) getPageAt(page);
    layout.setColumnCount(layout.getCellCountX());
    for (int i = 0; i < items.size(); ++i) {
        Object rawInfo = items.get(i);
        PendingAddItemInfo createItemInfo = null;
        PagedViewWidget widget = (PagedViewWidget) mLayoutInflater.inflate(R.layout.apps_customize_widget,
                layout, false);
        if (rawInfo instanceof AppWidgetProviderInfo) {
            // Fill in the widget information
            AppWidgetProviderInfo info = (AppWidgetProviderInfo) rawInfo;
            createItemInfo = new PendingAddWidgetInfo(info, null, null);

            // Determine the widget spans and min resize spans.
            int[] spanXY = Launcher.getSpanForWidget(mLauncher, info);
            createItemInfo.spanX = spanXY[0];
            createItemInfo.spanY = spanXY[1];
            int[] minSpanXY = Launcher.getMinSpanForWidget(mLauncher, info);
            createItemInfo.minSpanX = minSpanXY[0];
            createItemInfo.minSpanY = minSpanXY[1];

            widget.applyFromAppWidgetProviderInfo(info, -1, spanXY, getWidgetPreviewLoader());
            widget.setTag(createItemInfo);
            widget.setShortPressListener(this);
        } else if (rawInfo instanceof ResolveInfo) {
            // Fill in the shortcuts information
            ResolveInfo info = (ResolveInfo) rawInfo;
            createItemInfo = new PendingAddShortcutInfo(info.activityInfo);
            createItemInfo.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
            createItemInfo.componentName = new ComponentName(info.activityInfo.packageName,
                    info.activityInfo.name);
            widget.applyFromResolveInfo(mPackageManager, info, getWidgetPreviewLoader());
            widget.setTag(createItemInfo);
        }
        widget.setOnClickListener(this);
        widget.setOnLongClickListener(this);
        widget.setOnTouchListener(this);
        widget.setOnKeyListener(this);

        // Layout each widget
        int ix = i % mWidgetCountX;
        int iy = i / mWidgetCountX;
        GridLayout.LayoutParams lp = new GridLayout.LayoutParams(GridLayout.spec(iy, GridLayout.START),
                GridLayout.spec(ix, GridLayout.TOP));
        lp.width = cellWidth;
        lp.height = cellHeight;
        lp.setGravity(Gravity.TOP | Gravity.START);
        if (ix > 0)
            lp.leftMargin = mWidgetWidthGap;
        if (iy > 0)
            lp.topMargin = mWidgetHeightGap;
        layout.addView(widget, lp);
    }

    // wait until a call on onLayout to start loading, because
    // PagedViewWidget.getPreviewSize() will return 0 if it hasn't been laid out
    // TODO: can we do a measure/layout immediately?
    layout.setOnLayoutListener(new Runnable() {
        public void run() {
            // Load the widget previews
            int maxPreviewWidth = cellWidth;
            int maxPreviewHeight = cellHeight;
            if (layout.getChildCount() > 0) {
                PagedViewWidget w = (PagedViewWidget) layout.getChildAt(0);
                int[] maxSize = w.getPreviewSize();
                maxPreviewWidth = maxSize[0];
                maxPreviewHeight = maxSize[1];
            }

            getWidgetPreviewLoader().setPreviewSize(maxPreviewWidth, maxPreviewHeight, mWidgetSpacingLayout);
            if (immediate) {
                AsyncTaskPageData data = new AsyncTaskPageData(page, items, maxPreviewWidth, maxPreviewHeight,
                        null, null, getWidgetPreviewLoader());
                loadWidgetPreviewsInBackground(null, data);
                onSyncWidgetPageItems(data, immediate);
            } else {
                if (mInTransition) {
                    mDeferredPrepareLoadWidgetPreviewsTasks.add(this);
                } else {
                    prepareLoadWidgetPreviewsTask(page, items, maxPreviewWidth, maxPreviewHeight,
                            mWidgetCountX);
                }
            }
            layout.setOnLayoutListener(null);
        }
    });
}

From source file:com.zyk.launcher.AsyncTaskCallback.java

/**
 * Widget/*  ww  w. j a v  a 2  s  .  com*/
 * @param page
 * @param immediate
 */
public void syncWidgetPageItems(final int page, final boolean immediate) {
    int numItemsPerPage = mWidgetCountX * mWidgetCountY;

    final PagedViewGridLayout layout = (PagedViewGridLayout) getPageAt(page);

    // Calculate the dimensions of each cell we are giving to each widget
    final ArrayList<Object> items = new ArrayList<Object>();
    int contentWidth = mContentWidth - layout.getPaddingLeft() - layout.getPaddingRight();
    final int cellWidth = contentWidth / mWidgetCountX;
    int contentHeight = mContentHeight - layout.getPaddingTop() - layout.getPaddingBottom();

    final int cellHeight = contentHeight / mWidgetCountY;

    // Prepare the set of widgets to load previews for in the background
    int offset = page * numItemsPerPage;
    for (int i = offset; i < Math.min(offset + numItemsPerPage, mWidgets.size()); ++i) {
        items.add(mWidgets.get(i));
    }

    // Prepopulate the pages with the other widget info, and fill in the previews later
    layout.setColumnCount(layout.getCellCountX());
    for (int i = 0; i < items.size(); ++i) {
        Object rawInfo = items.get(i);
        PendingAddItemInfo createItemInfo = null;
        PagedViewWidget widget = (PagedViewWidget) mLayoutInflater.inflate(R.layout.apps_customize_widget,
                layout, false);
        if (rawInfo instanceof AppWidgetProviderInfo) {
            // Fill in the widget information
            AppWidgetProviderInfo info = (AppWidgetProviderInfo) rawInfo;
            createItemInfo = new PendingAddWidgetInfo(info, null, null);

            // Determine the widget spans and min resize spans.
            int[] spanXY = Launcher.getSpanForWidget(mLauncher, info);
            createItemInfo.spanX = spanXY[0];
            createItemInfo.spanY = spanXY[1];
            int[] minSpanXY = Launcher.getMinSpanForWidget(mLauncher, info);
            createItemInfo.minSpanX = minSpanXY[0];
            createItemInfo.minSpanY = minSpanXY[1];

            widget.applyFromAppWidgetProviderInfo(info, -1, spanXY, getWidgetPreviewLoader());
            widget.setTag(createItemInfo);
            widget.setShortPressListener(this);
        } else if (rawInfo instanceof ResolveInfo) {
            // Fill in the shortcuts information
            ResolveInfo info = (ResolveInfo) rawInfo;
            createItemInfo = new PendingAddShortcutInfo(info.activityInfo);
            createItemInfo.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
            createItemInfo.componentName = new ComponentName(info.activityInfo.packageName,
                    info.activityInfo.name);
            widget.applyFromResolveInfo(mPackageManager, info, getWidgetPreviewLoader());
            widget.setTag(createItemInfo);
        }
        widget.setOnClickListener(this);
        widget.setOnLongClickListener(this);
        widget.setOnTouchListener(this);
        widget.setOnKeyListener(this);

        // Layout each widget
        int ix = i % mWidgetCountX;
        int iy = i / mWidgetCountX;

        if (ix > 0) {
            View border = widget.findViewById(R.id.left_border);
            border.setVisibility(View.VISIBLE);
        }
        if (ix < mWidgetCountX - 1) {
            View border = widget.findViewById(R.id.right_border);
            border.setVisibility(View.VISIBLE);
        }

        GridLayout.LayoutParams lp = new GridLayout.LayoutParams(GridLayout.spec(iy, GridLayout.START),
                GridLayout.spec(ix, GridLayout.TOP));
        lp.width = cellWidth;
        lp.height = cellHeight;
        lp.setGravity(Gravity.TOP | Gravity.START);
        layout.addView(widget, lp);
    }

    // wait until a call on onLayout to start loading, because
    // PagedViewWidget.getPreviewSize() will return 0 if it hasn't been laid out
    // TODO: can we do a measure/layout immediately?
    layout.setOnLayoutListener(new Runnable() {
        public void run() {
            // Load the widget previews
            int maxPreviewWidth = cellWidth;
            int maxPreviewHeight = cellHeight;
            if (layout.getChildCount() > 0) {
                PagedViewWidget w = (PagedViewWidget) layout.getChildAt(0);
                int[] maxSize = w.getPreviewSize();
                maxPreviewWidth = maxSize[0];
                maxPreviewHeight = maxSize[1];
            }

            getWidgetPreviewLoader().setPreviewSize(maxPreviewWidth, maxPreviewHeight, mWidgetSpacingLayout);
            if (immediate) {
                AsyncTaskPageData data = new AsyncTaskPageData(page, items, maxPreviewWidth, maxPreviewHeight,
                        null, null, getWidgetPreviewLoader());
                loadWidgetPreviewsInBackground(null, data);
                onSyncWidgetPageItems(data, immediate);
            } else {
                if (mInTransition) {
                    mDeferredPrepareLoadWidgetPreviewsTasks.add(this);
                } else {
                    prepareLoadWidgetPreviewsTask(page, items, maxPreviewWidth, maxPreviewHeight,
                            mWidgetCountX);
                }
            }
            layout.setOnLayoutListener(null);
        }
    });
}

From source file:com.android.launcher2.AsyncTaskCallback.java

public void syncWidgetPageItems(final int page, final boolean immediate) {
    int numItemsPerPage = mWidgetCountX * mWidgetCountY;

    // Calculate the dimensions of each cell we are giving to each widget
    final ArrayList<Object> items = new ArrayList<Object>();
    int contentWidth = mWidgetSpacingLayout.getContentWidth();
    final int cellWidth = ((contentWidth - mPageLayoutPaddingLeft - mPageLayoutPaddingRight
            - ((mWidgetCountX - 1) * mWidgetWidthGap)) / mWidgetCountX);
    int contentHeight = mWidgetSpacingLayout.getContentHeight();
    final int cellHeight = ((contentHeight - mPageLayoutPaddingTop - mPageLayoutPaddingBottom
            - ((mWidgetCountY - 1) * mWidgetHeightGap)) / mWidgetCountY);

    // Prepare the set of widgets to load previews for in the background
    int offset = (page - mNumAppsPages) * numItemsPerPage;
    for (int i = offset; i < Math.min(offset + numItemsPerPage, mWidgets.size()); ++i) {
        items.add(mWidgets.get(i));//from   w w w .  j  a va  2s. co m
    }

    // Prepopulate the pages with the other widget info, and fill in the previews later
    final PagedViewGridLayout layout = (PagedViewGridLayout) getPageAt(page);
    layout.setColumnCount(layout.getCellCountX());
    for (int i = 0; i < items.size(); ++i) {
        Object rawInfo = items.get(i);
        PendingAddItemInfo createItemInfo = null;
        PagedViewWidget widget = (PagedViewWidget) mLayoutInflater.inflate(R.layout.apps_customize_widget,
                layout, false);
        if (rawInfo instanceof AppWidgetProviderInfo) {
            // Fill in the widget information
            AppWidgetProviderInfo info = (AppWidgetProviderInfo) rawInfo;
            createItemInfo = new PendingAddWidgetInfo(info, null, null);

            // Determine the widget spans and min resize spans.
            int[] spanXY = Launcher.getSpanForWidget(mLauncher, info);
            createItemInfo.spanX = spanXY[0];
            createItemInfo.spanY = spanXY[1];
            int[] minSpanXY = Launcher.getMinSpanForWidget(mLauncher, info);
            createItemInfo.minSpanX = minSpanXY[0];
            createItemInfo.minSpanY = minSpanXY[1];

            widget.applyFromAppWidgetProviderInfo(info, -1, spanXY);
            widget.setTag(createItemInfo);
            widget.setShortPressListener(this);
        } else if (rawInfo instanceof ResolveInfo) {
            // Fill in the shortcuts information
            ResolveInfo info = (ResolveInfo) rawInfo;
            createItemInfo = new PendingAddShortcutInfo(info.activityInfo);
            createItemInfo.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
            createItemInfo.componentName = new ComponentName(info.activityInfo.packageName,
                    info.activityInfo.name);
            widget.applyFromResolveInfo(mPackageManager, info);
            widget.setTag(createItemInfo);
        }
        widget.setOnClickListener(this);
        widget.setOnLongClickListener(this);
        widget.setOnTouchListener(this);
        widget.setOnKeyListener(this);

        // Layout each widget
        int ix = i % mWidgetCountX;
        int iy = i / mWidgetCountX;
        GridLayout.LayoutParams lp = new GridLayout.LayoutParams(GridLayout.spec(iy, GridLayout.LEFT),
                GridLayout.spec(ix, GridLayout.TOP));
        lp.width = cellWidth;
        lp.height = cellHeight;
        lp.setGravity(Gravity.TOP | Gravity.LEFT);
        if (ix > 0)
            lp.leftMargin = mWidgetWidthGap;
        if (iy > 0)
            lp.topMargin = mWidgetHeightGap;
        layout.addView(widget, lp);
    }

    // wait until a call on onLayout to start loading, because
    // PagedViewWidget.getPreviewSize() will return 0 if it hasn't been laid out
    // TODO: can we do a measure/layout immediately?
    layout.setOnLayoutListener(new Runnable() {
        public void run() {
            // Load the widget previews
            int maxPreviewWidth = cellWidth;
            int maxPreviewHeight = cellHeight;
            if (layout.getChildCount() > 0) {
                PagedViewWidget w = (PagedViewWidget) layout.getChildAt(0);
                int[] maxSize = w.getPreviewSize();
                maxPreviewWidth = maxSize[0];
                maxPreviewHeight = maxSize[1];
            }
            if (immediate) {
                AsyncTaskPageData data = new AsyncTaskPageData(page, items, maxPreviewWidth, maxPreviewHeight,
                        null, null);
                loadWidgetPreviewsInBackground(null, data);
                onSyncWidgetPageItems(data);
            } else {
                if (mInTransition) {
                    mDeferredPrepareLoadWidgetPreviewsTasks.add(this);
                } else {
                    prepareLoadWidgetPreviewsTask(page, items, maxPreviewWidth, maxPreviewHeight,
                            mWidgetCountX);
                }
            }
        }
    });
}