Example usage for android.widget GridLayout addView

List of usage examples for android.widget GridLayout addView

Introduction

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

Prototype

public void addView(View child) 

Source Link

Document

Adds a child view.

Usage

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();/*from   ww  w  .  j  ava2 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:com.syncedsynapse.kore2.utils.UIUtils.java

/**
 * Fills the standard cast info list, consisting of a {@link android.widget.GridLayout}
 * with actor images and a Textview with the name and the role of the additional cast.
 * The number of actor presented on the {@link android.widget.GridLayout} is controlled
 * through the global setting, and only actors with images are presented.
 * The rest are presented in the additionalCastView TextView
 *
 * @param context Activity/*from   www  .j a va 2 s. c o  m*/
 * @param castList Cast list
 * @param castListView GridLayout on which too show actors that have images
 * @param additionalCastTitleView View with additional cast title
 * @param additionalCastView Additional cast
 */
public static void setupCastInfo(final Context context, List<VideoType.Cast> castList, GridLayout castListView,
        TextView additionalCastTitleView, TextView additionalCastView) {
    HostManager hostManager = HostManager.getInstance(context);
    Resources resources = context.getResources();
    DisplayMetrics displayMetrics = new DisplayMetrics();
    WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    windowManager.getDefaultDisplay().getMetrics(displayMetrics);

    View.OnClickListener castListClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Utils.openImdbForPerson(context, (String) v.getTag());
        }
    };

    castListView.removeAllViews();
    int numColumns = castListView.getColumnCount();

    int layoutMarginPx = 2 * resources.getDimensionPixelSize(R.dimen.remote_content_hmargin);
    int imageMarginPx = 2 * resources.getDimensionPixelSize(R.dimen.image_grid_margin);
    int imageWidth = (displayMetrics.widthPixels - layoutMarginPx - numColumns * imageMarginPx) / numColumns;
    int imageHeight = (int) (imageWidth * 1.2);

    List<VideoType.Cast> noPicturesCastList = new ArrayList<VideoType.Cast>();
    int maxCastPictures = Settings.DEFAULT_MAX_CAST_PICTURES;
    int currentPictureNumber = 0;
    for (int i = 0; i < castList.size(); i++) {
        VideoType.Cast actor = castList.get(i);

        if (((maxCastPictures == -1) || (currentPictureNumber < maxCastPictures))
                && (actor.thumbnail != null)) {
            // Present the picture
            currentPictureNumber++;
            View castView = LayoutInflater.from(context).inflate(R.layout.grid_item_cast, castListView, false);
            ImageView castPicture = (ImageView) castView.findViewById(R.id.picture);
            TextView castName = (TextView) castView.findViewById(R.id.name);
            TextView castRole = (TextView) castView.findViewById(R.id.role);

            castView.getLayoutParams().width = imageWidth;
            castView.getLayoutParams().height = (int) (imageHeight * 1.2);
            castView.setTag(actor.name);
            castView.setOnClickListener(castListClickListener);

            castName.setText(actor.name);
            castRole.setText(actor.role);
            UIUtils.loadImageWithCharacterAvatar(context, hostManager, actor.thumbnail, actor.name, castPicture,
                    imageWidth, imageHeight);
            castListView.addView(castView);
        } else {
            noPicturesCastList.add(actor);
        }
    }

    // Additional cast
    if (noPicturesCastList.size() > 0) {
        additionalCastTitleView.setVisibility(View.VISIBLE);
        additionalCastView.setVisibility(View.VISIBLE);
        StringBuilder castListText = new StringBuilder();
        boolean first = true;
        for (VideoType.Cast cast : noPicturesCastList) {
            if (!first)
                castListText.append("\n");
            first = false;
            if (!TextUtils.isEmpty(cast.role)) {
                castListText.append(
                        String.format(context.getString(R.string.cast_list_text), cast.name, cast.role));
            } else {
                castListText.append(cast.name);
            }
        }
        additionalCastView.setText(castListText);
    } else {
        additionalCastTitleView.setVisibility(View.GONE);
        additionalCastView.setVisibility(View.GONE);
    }
}

From source file:org.xbmc.kore.utils.UIUtils.java

/**
 * Fills the standard cast info list, consisting of a {@link android.widget.GridLayout}
 * with actor images and a Textview with the name and the role of the additional cast.
 * The number of actor presented on the {@link android.widget.GridLayout} is controlled
 * through the global setting, and only actors with images are presented.
 * The rest are presented in the additionalCastView TextView
 *
 * @param activity Activity//from  www  .  j a v  a2 s  .  co  m
 * @param castList Cast list
 * @param castListView GridLayout on which too show actors that have images
 */
public static void setupCastInfo(final Activity activity, List<VideoType.Cast> castList,
        GridLayout castListView, final Intent allCastActivityLaunchIntent) {
    HostManager hostManager = HostManager.getInstance(activity);
    Resources resources = activity.getResources();
    DisplayMetrics displayMetrics = new DisplayMetrics();
    WindowManager windowManager = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);
    windowManager.getDefaultDisplay().getMetrics(displayMetrics);

    View.OnClickListener castListClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Utils.openImdbForPerson(activity, (String) v.getTag());
        }
    };

    castListView.removeAllViews();
    int numColumns = castListView.getColumnCount();
    int numRows = resources.getInteger(R.integer.cast_grid_view_rows);
    int maxCastPictures = numColumns * numRows;

    int layoutMarginPx = 2 * resources.getDimensionPixelSize(R.dimen.remote_content_hmargin);
    int imageMarginPx = 2 * resources.getDimensionPixelSize(R.dimen.image_grid_margin);
    int imageWidth = (displayMetrics.widthPixels - layoutMarginPx - numColumns * imageMarginPx) / numColumns;
    int imageHeight = (int) (imageWidth * 1.5);

    for (int i = 0; i < Math.min(castList.size(), maxCastPictures); i++) {
        VideoType.Cast actor = castList.get(i);

        View castView = LayoutInflater.from(activity).inflate(R.layout.grid_item_cast, castListView, false);
        ImageView castPicture = (ImageView) castView.findViewById(R.id.picture);
        TextView castName = (TextView) castView.findViewById(R.id.name);
        TextView castRole = (TextView) castView.findViewById(R.id.role);

        castView.getLayoutParams().width = imageWidth;
        castView.getLayoutParams().height = imageHeight;
        castView.setTag(actor.name);

        UIUtils.loadImageWithCharacterAvatar(activity, hostManager, actor.thumbnail, actor.name, castPicture,
                imageWidth, imageHeight);

        if ((i == maxCastPictures - 1) && (castList.size() > i + 1)) {
            View castNameGroup = castView.findViewById(R.id.cast_name_group);
            View allCastGroup = castView.findViewById(R.id.all_cast_group);
            TextView remainingCastCount = (TextView) castView.findViewById(R.id.remaining_cast_count);

            castNameGroup.setVisibility(View.GONE);
            allCastGroup.setVisibility(View.VISIBLE);
            remainingCastCount.setText(String.format(activity.getString(R.string.remaining_cast_count),
                    castList.size() - maxCastPictures + 1));
            castView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    activity.startActivity(allCastActivityLaunchIntent);
                    activity.overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                }
            });
        } else {
            castName.setText(actor.name);
            castRole.setText(actor.role);
            castView.setOnClickListener(castListClickListener);
        }

        castListView.addView(castView);
    }
}

From source file:com.retroteam.studio.retrostudio.EditorLandscape.java

/**
 * Create all the views associated with a track.
 * @param waveDrawableID// w  w w.j  av a 2 s . c om
 * @param projectLoad
 * @return
 */

private ImageView addTrack(int waveDrawableID, boolean projectLoad) {
    //add the track with the measure adder to the view
    //get layout
    LinearLayout track_layout = (LinearLayout) findViewById(R.id.track_layout);

    //create track container
    HorizontalScrollView track_container = new HorizontalScrollView(getApplicationContext());
    track_container.setLayoutParams(new HorizontalScrollView.LayoutParams(
            HorizontalScrollView.LayoutParams.MATCH_PARENT, displaysize.y / 4));
    track_container.setBackground(getResources().getDrawable(R.color.track_container_bg));

    //create grid layout
    GridLayout track_grid = new GridLayout(getApplicationContext());
    track_grid.setColumnCount(100);
    track_grid.setRowCount(1);
    track_grid.setOrientation(GridLayout.HORIZONTAL);
    track_grid.setId(R.id.track_grid);

    //create linear layout for track id and wave
    LinearLayout track_identifier = new LinearLayout(getApplicationContext());
    track_identifier.setLayoutParams(new LinearLayout.LayoutParams(displaysize.x / 14, displaysize.y / 4));
    track_identifier.setOrientation(LinearLayout.VERTICAL);
    track_identifier.setBackgroundColor(getResources().getColor(R.color.black_overlay));

    //create textview for linear layout
    TextView track_num = new TextView(getApplicationContext());
    track_num.setText("1");
    track_num.setTextSize(45);
    track_num.setGravity(Gravity.CENTER | Gravity.CENTER_VERTICAL);

    //create imageview for linear layout
    ImageView track_type = new ImageView(getApplicationContext());
    track_type.setImageResource(waveDrawableID);
    track_type.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.MATCH_PARENT));

    //create "add measure" for grid layout
    ImageView add_measure = new ImageView(getApplicationContext());
    add_measure.setImageResource(R.drawable.measure_new);
    add_measure.setLayoutParams(new LinearLayout.LayoutParams((int) (displaysize.x / 3.32),
            LinearLayout.LayoutParams.MATCH_PARENT));
    if (projectLoad) {
        add_measure.setTag(R.id.TAG_ROW, trackReloadCounter);
        add_measure.setId(trackReloadCounter + 4200);
    } else {
        add_measure.setTag(R.id.TAG_ROW, theproject.size() - 1);
        add_measure.setId(theproject.size() - 1 + 4200);
    }

    add_measure.setTag(R.id.TAG_COLUMN, 0);
    add_measure.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            addMeasure(v, false);

        }
    });

    track_identifier.addView(track_num);
    if (projectLoad) {
        track_num.setText(Integer.toString(trackReloadCounter + 1));
        trackReloadCounter += 1;
    } else {
        track_num.setText(Integer.toString(theproject.size()));
    }
    track_num.setTextSize(45);
    track_identifier.addView(track_type);

    track_grid.addView(track_identifier);
    track_grid.addView(add_measure);

    track_container.addView(track_grid);

    track_layout.addView(track_container);

    return add_measure;

}

From source file:org.rm3l.ddwrt.tiles.status.wireless.WirelessClientsTile.java

/**
 * Called when a previously created loader has finished its load.  Note
 * that normally an application is <em>not</em> allowed to commit fragment
 * transactions while in this call, since it can happen after an
 * activity's state is saved.  See {@link android.support.v4.app.FragmentManager#beginTransaction()
 * FragmentManager.openTransaction()} for further discussion on this.
 * <p/>/*from w  ww  .  j  a  v a 2  s. com*/
 * <p>This function is guaranteed to be called prior to the release of
 * the last data that was supplied for this Loader.  At this point
 * you should remove all use of the old data (since it will be released
 * soon), but should not do your own release of the data since its Loader
 * owns it and will take care of that.  The Loader will take care of
 * management of its data so you don't have to.  In particular:
 * <p/>
 * <ul>
 * <li> <p>The Loader will monitor for changes to the data, and report
 * them to you through new calls here.  You should not monitor the
 * data yourself.  For example, if the data is a {@link android.database.Cursor}
 * and you place it in a {@link android.widget.CursorAdapter}, use
 * the {@link android.widget.CursorAdapter#CursorAdapter(android.content.Context,
 * android.database.Cursor, int)} constructor <em>without</em> passing
 * in either {@link android.widget.CursorAdapter#FLAG_AUTO_REQUERY}
 * or {@link android.widget.CursorAdapter#FLAG_REGISTER_CONTENT_OBSERVER}
 * (that is, use 0 for the flags argument).  This prevents the CursorAdapter
 * from doing its own observing of the Cursor, which is not needed since
 * when a change happens you will get a new Cursor throw another call
 * here.
 * <li> The Loader will release the data once it knows the application
 * is no longer using it.  For example, if the data is
 * a {@link android.database.Cursor} from a {@link android.content.CursorLoader},
 * you should not call close() on it yourself.  If the Cursor is being placed in a
 * {@link android.widget.CursorAdapter}, you should use the
 * {@link android.widget.CursorAdapter#swapCursor(android.database.Cursor)}
 * method so that the old Cursor is not closed.
 * </ul>
 *
 * @param loader The Loader that has finished.
 * @param data   The data generated by the Loader.
 */
@Override
public void onLoadFinished(Loader<ClientDevices> loader, ClientDevices data) {
    Log.d(LOG_TAG, "onLoadFinished: loader=" + loader + " / data=" + data);

    layout.findViewById(R.id.tile_status_wireless_clients_loading_view).setVisibility(View.GONE);
    layout.findViewById(R.id.tile_status_wireless_clients_layout_list_container).setVisibility(View.VISIBLE);
    layout.findViewById(R.id.tile_status_wireless_clients_togglebutton_container).setVisibility(View.VISIBLE);

    if (data == null || (data.getDevices().isEmpty()
            && !(data.getException() instanceof DDWRTTileAutoRefreshNotAllowedException))) {
        data = new ClientDevices().setException(new DDWRTNoDataException("No Data!"));
    }

    @NotNull
    final TextView errorPlaceHolderView = (TextView) this.layout
            .findViewById(R.id.tile_status_wireless_clients_error);

    @Nullable
    final Exception exception = data.getException();

    if (!(exception instanceof DDWRTTileAutoRefreshNotAllowedException)) {

        if (exception == null) {
            errorPlaceHolderView.setVisibility(View.GONE);
        }

        final GridLayout clientsContainer = (GridLayout) this.layout
                .findViewById(R.id.tile_status_wireless_clients_layout_list_container);
        clientsContainer.removeAllViews();
        clientsContainer.setBackgroundColor(
                mParentFragmentActivity.getResources().getColor(android.R.color.transparent));

        final Set<Device> devices = data.getDevices(MAX_CLIENTS_TO_SHOW_IN_TILE);
        final int themeBackgroundColor = getThemeBackgroundColor(mParentFragmentActivity, mRouter.getUuid());
        final boolean isThemeLight = isThemeLight(mParentFragmentActivity, mRouter.getUuid());
        for (final Device device : devices) {

            final CardView cardView = (CardView) mParentFragmentActivity.getLayoutInflater()
                    .inflate(R.layout.tile_status_wireless_client, null);

            //Create Options Menu
            final ImageButton tileMenu = (ImageButton) cardView
                    .findViewById(R.id.tile_status_wireless_client_device_menu);

            if (!isThemeLight) {
                //Set menu background to white
                tileMenu.setImageResource(R.drawable.abs__ic_menu_moreoverflow_normal_holo_dark);
            }

            cardView.setCardBackgroundColor(themeBackgroundColor);

            //Add padding to CardView on v20 and before to prevent intersections between the Card content and rounded corners.
            cardView.setPreventCornerOverlap(true);
            //Add padding in API v21+ as well to have the same measurements with previous versions.
            cardView.setUseCompatPadding(true);

            final TextView deviceName = (TextView) cardView
                    .findViewById(R.id.tile_status_wireless_client_device_name);
            final String name = device.getName();
            deviceName.setText(name);

            final TextView deviceMac = (TextView) cardView
                    .findViewById(R.id.tile_status_wireless_client_device_mac);
            final String macAddress = device.getMacAddress();
            deviceMac.setText(macAddress);

            final TextView deviceIp = (TextView) cardView
                    .findViewById(R.id.tile_status_wireless_client_device_ip);
            final String ipAddress = device.getIpAddress();
            final boolean isThisDevice = (ipAddress != null && ipAddress.equals(mCurrentIpAddress));
            deviceIp.setText(ipAddress);
            if (isThisDevice) {
                final View thisDevice = cardView.findViewById(R.id.tile_status_wireless_client_device_this);
                if (isThemeLight) {
                    //Set text color to blue
                    ((TextView) thisDevice)
                            .setTextColor(mParentFragmentActivity.getResources().getColor(R.color.blue));
                }
                thisDevice.setVisibility(View.VISIBLE);
            }

            cardView.setOnClickListener(new DeviceOnClickListener(device));

            clientsContainer.addView(cardView);

            tileMenu.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    final PopupMenu popup = new PopupMenu(mParentFragmentActivity, v);
                    popup.setOnMenuItemClickListener(new DeviceOnMenuItemClickListener(device));
                    final MenuInflater inflater = popup.getMenuInflater();

                    final Menu menu = popup.getMenu();

                    inflater.inflate(R.menu.tile_status_wireless_client_options, menu);

                    if (isThisDevice) {
                        //WOL not needed as this is the current device
                        menu.findItem(R.id.tile_status_wireless_client_wol).setEnabled(false);
                    }

                    popup.show();
                }
            });
        }

        final Button showMore = (Button) this.layout.findViewById(R.id.tile_status_wireless_clients_show_more);
        //Whether to display 'Show more' button
        if (data.getDevicesCount() > MAX_CLIENTS_TO_SHOW_IN_TILE) {
            showMore.setVisibility(View.VISIBLE);
            showMore.setOnClickListener(this);
        } else {
            showMore.setVisibility(View.GONE);
        }

    }

    if (exception != null && !(exception instanceof DDWRTTileAutoRefreshNotAllowedException)) {
        //noinspection ThrowableResultOfMethodCallIgnored
        final Throwable rootCause = Throwables.getRootCause(exception);
        errorPlaceHolderView.setText("Error: " + (rootCause != null ? rootCause.getMessage() : "null"));
        final Context parentContext = this.mParentFragmentActivity;
        errorPlaceHolderView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                //noinspection ThrowableResultOfMethodCallIgnored
                if (rootCause != null) {
                    Toast.makeText(parentContext, rootCause.getMessage(), Toast.LENGTH_LONG).show();
                }
            }
        });
        errorPlaceHolderView.setVisibility(View.VISIBLE);
    }

    doneWithLoaderInstance(this, loader, R.id.tile_status_wireless_clients_togglebutton_title,
            R.id.tile_status_wireless_clients_togglebutton_separator);

    Log.d(LOG_TAG, "onLoadFinished(): done loading!");
}

From source file:org.xbmc.kore.ui.sections.video.TVShowProgressFragment.java

/**
 * Display next episode list// w  ww.j av  a  2s .  co m
 *
 * @param cursor Cursor with the data
 */
@TargetApi(21)
private void displayNextEpisodeList(Cursor cursor) {
    TextView nextEpisodeTitle = (TextView) getActivity().findViewById(R.id.next_episode_title);
    GridLayout nextEpisodeList = (GridLayout) getActivity().findViewById(R.id.next_episode_list);

    if (cursor.moveToFirst()) {
        nextEpisodeTitle.setVisibility(View.VISIBLE);
        nextEpisodeList.setVisibility(View.VISIBLE);

        HostManager hostManager = HostManager.getInstance(getActivity());

        View.OnClickListener episodeClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AbstractInfoFragment.DataHolder vh = (AbstractInfoFragment.DataHolder) v.getTag();
                listenerActivity.onNextEpisodeSelected(itemId, vh);
            }
        };

        // Get the art dimensions
        Resources resources = getActivity().getResources();
        int artWidth = (int) (resources.getDimension(R.dimen.detail_poster_width_square)
                / UIUtils.IMAGE_RESIZE_FACTOR);
        int artHeight = (int) (resources.getDimension(R.dimen.detail_poster_height_square)
                / UIUtils.IMAGE_RESIZE_FACTOR);

        nextEpisodeList.removeAllViews();
        do {
            int episodeId = cursor.getInt(NextEpisodesListQuery.EPISODEID);
            String title = cursor.getString(NextEpisodesListQuery.TITLE);
            String seasonEpisode = String.format(getString(R.string.season_episode),
                    cursor.getInt(NextEpisodesListQuery.SEASON), cursor.getInt(NextEpisodesListQuery.EPISODE));
            int runtime = cursor.getInt(NextEpisodesListQuery.RUNTIME) / 60;
            String duration = runtime > 0
                    ? String.format(getString(R.string.minutes_abbrev), String.valueOf(runtime)) + "  |  "
                            + cursor.getString(NextEpisodesListQuery.FIRSTAIRED)
                    : cursor.getString(NextEpisodesListQuery.FIRSTAIRED);
            String thumbnail = cursor.getString(NextEpisodesListQuery.THUMBNAIL);

            View episodeView = LayoutInflater.from(getActivity()).inflate(R.layout.list_item_next_episode,
                    nextEpisodeList, false);

            ImageView artView = (ImageView) episodeView.findViewById(R.id.art);
            TextView titleView = (TextView) episodeView.findViewById(R.id.title);
            TextView detailsView = (TextView) episodeView.findViewById(R.id.details);
            TextView durationView = (TextView) episodeView.findViewById(R.id.duration);

            titleView.setText(title);
            detailsView.setText(seasonEpisode);
            durationView.setText(duration);

            UIUtils.loadImageWithCharacterAvatar(getActivity(), hostManager, thumbnail, title, artView,
                    artWidth, artHeight);

            AbstractInfoFragment.DataHolder vh = new AbstractInfoFragment.DataHolder(episodeId);
            vh.setTitle(title);
            vh.setUndertitle(seasonEpisode);
            episodeView.setTag(vh);
            episodeView.setOnClickListener(episodeClickListener);

            // For the popupmenu
            ImageView contextMenu = (ImageView) episodeView.findViewById(R.id.list_context_menu);
            contextMenu.setTag(episodeId);
            contextMenu.setOnClickListener(contextlistItemMenuClickListener);

            nextEpisodeList.addView(episodeView);
        } while (cursor.moveToNext());
    } else {
        // No episodes, hide views
        nextEpisodeTitle.setVisibility(View.GONE);
        nextEpisodeList.setVisibility(View.GONE);
    }
}

From source file:org.xbmc.kore.ui.sections.video.TVShowProgressFragment.java

/**
 * Display the seasons list//from ww  w . ja  v  a2s.co  m
 *
 * @param cursor Cursor with the data
 */
private void displaySeasonList(Cursor cursor) {
    TextView seasonsListTitle = (TextView) getActivity().findViewById(R.id.seasons_title);
    GridLayout seasonsList = (GridLayout) getActivity().findViewById(R.id.seasons_list);

    if (cursor.moveToFirst()) {
        seasonsListTitle.setVisibility(View.VISIBLE);
        seasonsList.setVisibility(View.VISIBLE);

        HostManager hostManager = HostManager.getInstance(getActivity());

        View.OnClickListener seasonListClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                listenerActivity.onSeasonSelected(itemId, (int) v.getTag());
            }
        };

        // Get the art dimensions
        Resources resources = getActivity().getResources();
        int artWidth = (int) (resources.getDimension(R.dimen.seasonlist_art_width)
                / UIUtils.IMAGE_RESIZE_FACTOR);
        int artHeight = (int) (resources.getDimension(R.dimen.seasonlist_art_heigth)
                / UIUtils.IMAGE_RESIZE_FACTOR);

        // Get theme colors
        Resources.Theme theme = getActivity().getTheme();
        TypedArray styledAttributes = theme
                .obtainStyledAttributes(new int[] { R.attr.colorinProgress, R.attr.colorFinished });

        int inProgressColor = styledAttributes.getColor(styledAttributes.getIndex(0),
                resources.getColor(R.color.orange_500));
        int finishedColor = styledAttributes.getColor(styledAttributes.getIndex(1),
                resources.getColor(R.color.green_400));
        styledAttributes.recycle();

        seasonsList.removeAllViews();
        do {
            int seasonNumber = cursor.getInt(SeasonsListQuery.SEASON);
            String thumbnail = cursor.getString(SeasonsListQuery.THUMBNAIL);
            int numEpisodes = cursor.getInt(SeasonsListQuery.EPISODE);
            int watchedEpisodes = cursor.getInt(SeasonsListQuery.WATCHEDEPISODES);

            View seasonView = LayoutInflater.from(getActivity()).inflate(R.layout.grid_item_season, seasonsList,
                    false);

            ImageView seasonPictureView = (ImageView) seasonView.findViewById(R.id.art);
            TextView seasonNumberView = (TextView) seasonView.findViewById(R.id.season);
            TextView seasonEpisodesView = (TextView) seasonView.findViewById(R.id.episodes);
            ProgressBar seasonProgressBar = (ProgressBar) seasonView.findViewById(R.id.season_progress_bar);

            seasonNumberView
                    .setText(String.format(getActivity().getString(R.string.season_number), seasonNumber));
            seasonEpisodesView.setText(String.format(getActivity().getString(R.string.num_episodes),
                    numEpisodes, numEpisodes - watchedEpisodes));
            seasonProgressBar.setMax(numEpisodes);
            seasonProgressBar.setProgress(watchedEpisodes);

            if (Utils.isLollipopOrLater()) {
                int watchedColor = (numEpisodes - watchedEpisodes == 0) ? finishedColor : inProgressColor;
                seasonProgressBar.setProgressTintList(ColorStateList.valueOf(watchedColor));
            }

            UIUtils.loadImageWithCharacterAvatar(getActivity(), hostManager, thumbnail,
                    String.valueOf(seasonNumber), seasonPictureView, artWidth, artHeight);

            seasonView.setTag(seasonNumber);
            seasonView.setOnClickListener(seasonListClickListener);
            seasonsList.addView(seasonView);
        } while (cursor.moveToNext());
    } else {
        // No seasons, hide views
        seasonsListTitle.setVisibility(View.GONE);
        seasonsList.setVisibility(View.GONE);
    }
}