Example usage for android.widget ImageView getLayoutParams

List of usage examples for android.widget ImageView getLayoutParams

Introduction

In this page you can find the example usage for android.widget ImageView getLayoutParams.

Prototype

@ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
public ViewGroup.LayoutParams getLayoutParams() 

Source Link

Document

Get the LayoutParams associated with this view.

Usage

From source file:com.forrestguice.suntimeswidget.SuntimesActivity.java

private void adjustNoteIconSize(NoteData note, ImageView icon) {
    Resources resources = getResources();
    int iconWidth = (int) resources.getDimension(R.dimen.sunIconLarge_width);
    int iconHeight = ((note.noteIconResource == R.drawable.ic_noon_large) ? iconWidth
            : (int) resources.getDimension(R.dimen.sunIconLarge_height));

    ViewGroup.LayoutParams iconParams = icon.getLayoutParams();
    iconParams.width = iconWidth;//from  w  ww.j a v a2  s . com
    iconParams.height = iconHeight;
}

From source file:com.pongme.utils.ImageDownloader.java

/**
 * @param url//  w  ww . j ava2  s  . c  om
 *            The URL of the image that will be retrieved from the cache.
 * @return The cached bitmap or null if it was not found.
 */
private Bitmap getBitmapFromCache(String url, ImageView imageView, BitmapDrawable tempImage) {
    // First try the hard reference cache
    synchronized (sHardBitmapCache) {
        final Bitmap bitmap = sHardBitmapCache.get(url);
        if (bitmap != null) {
            // Bitmap found in hard cache
            // Move element to first position, so that it is removed last
            sHardBitmapCache.remove(url);
            sHardBitmapCache.put(url, bitmap);
            return bitmap;
        }
    }

    // Then try the hard reference cache for big Images
    synchronized (sHardBitmapCacheBigImg) {
        final Bitmap bitmap = sHardBitmapCacheBigImg.get(url);
        if (bitmap != null) {
            // Bitmap found in hard cache
            // Move element to first position, so that it is removed last
            sHardBitmapCacheBigImg.remove(url);
            sHardBitmapCacheBigImg.put(url, bitmap);
            return bitmap;
        }
    }

    // Then try the soft reference cache
    WeakReference<Bitmap> bitmapReference = sSoftBitmapCache.get(url);
    if (bitmapReference != null) {
        final Bitmap bitmap = bitmapReference.get();
        if (bitmap != null) {
            return bitmap;
        } else {
            // Soft reference has been Garbage Collected
            sSoftBitmapCache.remove(url);
        }
    }

    synchronized (sFileCache) {

        String filename = sFileCache.get(url);
        if (filename != null) {
            LayoutParams params = imageView.getLayoutParams();
            int width = 0;
            int height = 0;
            if (params != null) {
                width = params.width;
                height = params.height;
            }

            Bitmap bitmap = getBitmapFromFile(sFileCache.getCachedFile(filename), width, height);
            if (bitmap != null) {
                sFileCache.refresh(url, filename);
                addBitmapToCache(url, bitmap);
                return bitmap;
            }
        }
    }

    return null;
}

From source file:im.neon.adapters.VectorMessagesAdapter.java

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View view = super.getView(position, convertView, parent);

    if (null != view) {
        view.setBackgroundColor(Color.TRANSPARENT);
    }//from   ww w  . ja  va2s  .c o  m

    ImageView e2eIconView = (ImageView) view.findViewById(R.id.message_adapter_e2e_icon);
    View senderMargin = view.findViewById(R.id.e2e_sender_margin);
    View senderNameView = view.findViewById(R.id.messagesAdapter_sender);

    // GA issue
    if (position >= getCount()) {
        return view;
    }

    MessageRow row = getItem(position);
    final Event event = row.getEvent();

    if (mE2eIconByEventId.containsKey(event.eventId)) {
        senderMargin.setVisibility(senderNameView.getVisibility());
        e2eIconView.setVisibility(View.VISIBLE);
        e2eIconView.setImageResource(mE2eIconByEventId.get(event.eventId));

        int type = getItemViewType(position);

        if ((type == ROW_TYPE_IMAGE) || (type == ROW_TYPE_VIDEO)) {
            View bodyLayoutView = view.findViewById(org.matrix.androidsdk.R.id.messagesAdapter_body_layout);
            ViewGroup.MarginLayoutParams bodyLayout = (ViewGroup.MarginLayoutParams) bodyLayoutView
                    .getLayoutParams();
            ViewGroup.MarginLayoutParams e2eIconViewLayout = (ViewGroup.MarginLayoutParams) e2eIconView
                    .getLayoutParams();

            e2eIconViewLayout.setMargins(bodyLayout.leftMargin, e2eIconViewLayout.topMargin,
                    e2eIconViewLayout.rightMargin, e2eIconViewLayout.bottomMargin);
            bodyLayout.setMargins(4, bodyLayout.topMargin, bodyLayout.rightMargin, bodyLayout.bottomMargin);
            e2eIconView.setLayoutParams(e2eIconViewLayout);
            bodyLayoutView.setLayoutParams(bodyLayout);
        }

        e2eIconView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != mVectorMessagesAdapterEventsListener) {
                    mVectorMessagesAdapterEventsListener.onE2eIconClick(event,
                            mE2eDeviceByEventId.get(event.eventId));
                }
            }
        });
    } else {
        e2eIconView.setVisibility(View.GONE);
        senderMargin.setVisibility(View.GONE);
    }

    return view;
}

From source file:com.thousandthoughts.tutorials.SensorFusionActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);/*from w ww  .j  a  v a 2 s  .c o m*/
    layout = (RelativeLayout) findViewById(R.id.mainlayout);
    IP1 = "";
    IP2 = "";
    angle1 = 0.0f;
    angle2 = 0.0f;
    gyroOrientation[0] = 0.0f;
    gyroOrientation[1] = 0.0f;
    gyroOrientation[2] = 0.0f;

    // initialise gyroMatrix with identity matrix
    gyroMatrix[0] = 1.0f;
    gyroMatrix[1] = 0.0f;
    gyroMatrix[2] = 0.0f;
    gyroMatrix[3] = 0.0f;
    gyroMatrix[4] = 1.0f;
    gyroMatrix[5] = 0.0f;
    gyroMatrix[6] = 0.0f;
    gyroMatrix[7] = 0.0f;
    gyroMatrix[8] = 1.0f;

    // get sensorManager and initialise sensor listeners
    mSensorManager = (SensorManager) this.getSystemService(SENSOR_SERVICE);
    initListeners();

    // wait for one second until gyroscope and magnetometer/accelerometer
    // data is initialised then scedule the complementary filter task
    fuseTimer.scheduleAtFixedRate(new calculateFusedOrientationTask(), 1000, TIME_CONSTANT);

    // GUI stuff
    try {
        client1 = new MyCoapClient(this.IP1);
        client2 = new MyCoapClient(this.IP2);
    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    json = new JSONObject();
    mHandler = new Handler();
    radioSelection = 0;
    d.setRoundingMode(RoundingMode.HALF_UP);
    d.setMaximumFractionDigits(3);
    d.setMinimumFractionDigits(3);

    /// Application layout here only

    RelativeLayout.LayoutParams left = new RelativeLayout.LayoutParams(
            android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
    RelativeLayout.LayoutParams right = new RelativeLayout.LayoutParams(
            android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
    RelativeLayout.LayoutParams up = new RelativeLayout.LayoutParams(
            android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
    RelativeLayout.LayoutParams down = new RelativeLayout.LayoutParams(
            android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
    RelativeLayout.LayoutParams button1 = new RelativeLayout.LayoutParams(
            android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
    RelativeLayout.LayoutParams button2 = new RelativeLayout.LayoutParams(
            android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
    RelativeLayout.LayoutParams text1 = new RelativeLayout.LayoutParams(
            android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
    RelativeLayout.LayoutParams text2 = new RelativeLayout.LayoutParams(
            android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
    ImageView img_left = new ImageView(this);
    ImageView img_right = new ImageView(this);
    ImageView img_up = new ImageView(this);
    ImageView img_down = new ImageView(this);
    ImageView img_button1 = new ImageView(this);
    ImageView img_button2 = new ImageView(this);
    final EditText edittext1 = new EditText(this);
    final EditText edittext2 = new EditText(this);
    img_left.setImageResource(R.drawable.left_button);
    img_right.setImageResource(R.drawable.right_button);
    img_up.setImageResource(R.drawable.up);
    img_down.setImageResource(R.drawable.down);
    img_button1.setImageResource(R.drawable.button);
    img_button2.setImageResource(R.drawable.button);

    left.setMargins(0, 66, 0, 0);
    right.setMargins(360, 66, 0, 0);
    up.setMargins(240, 90, 0, 0);
    down.setMargins(240, 240, 0, 0);
    button1.setMargins(440, 800, 0, 0);
    button2.setMargins(440, 900, 0, 0);
    text1.setMargins(5, 800, 0, 0);
    text2.setMargins(5, 900, 0, 0);

    layout.addView(img_left, left);
    layout.addView(img_right, right);
    layout.addView(img_up, up);
    layout.addView(img_down, down);
    layout.addView(img_button1, button1);
    layout.addView(edittext1, text1);
    layout.addView(img_button2, button2);
    layout.addView(edittext2, text2);

    img_left.getLayoutParams().height = 560;
    img_left.getLayoutParams().width = 280;
    img_right.getLayoutParams().height = 560;
    img_right.getLayoutParams().width = 280;
    img_up.getLayoutParams().height = 150;
    img_up.getLayoutParams().width = 150;
    img_down.getLayoutParams().height = 150;
    img_down.getLayoutParams().width = 150;
    img_button1.getLayoutParams().height = 100;
    img_button1.getLayoutParams().width = 200;
    edittext1.getLayoutParams().width = 400;
    edittext1.setText("84.248.76.84");
    edittext2.setText("84.248.76.84");
    img_button2.getLayoutParams().height = 100;
    img_button2.getLayoutParams().width = 200;
    edittext2.getLayoutParams().width = 400;

    /////////// Define and Remember Position for EACH PHYSICAL OBJECTS (LAPTOPS) /////////////////////
    img_button1.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View view, MotionEvent event) {
            // TODO Auto-generated method stub
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                // POSITION OF LAPTOP 1 IS REMEMBERED
                angle1 = fusedOrientation[0];
                IP1 = edittext1.getText().toString();
                try {
                    // CREATE CLIENT CONNECT TO FIRST LAPTOP
                    client1 = new MyCoapClient(IP1);
                } catch (UnknownHostException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                break;
            case MotionEvent.ACTION_MOVE:
                break;
            case MotionEvent.ACTION_UP:
                //view.setImageResource(R.drawable.left_button);
                break;
            }
            return true;
        }

    });

    img_button2.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View view, MotionEvent event) {
            // TODO Auto-generated method stub
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                // POSITION OF LAPTOP 2 IS REMEMBERED
                angle2 = fusedOrientation[0];
                IP2 = edittext2.getText().toString();
                try {
                    // CREATE CLIENT CONNECT TO SECOND LAPTOP
                    client2 = new MyCoapClient(IP2);
                } catch (UnknownHostException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                break;
            case MotionEvent.ACTION_MOVE:
                break;
            case MotionEvent.ACTION_UP:
                break;
            }
            return true;
        }

    });

    img_left.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            ImageView view = (ImageView) v;
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                view.setImageResource(R.drawable.left_button_press);

                ///////////////////// PERFORM CLICK ACTION BASED ON POSITION OF 2 PHYSICAL OBJECTS (LAPTOPs) HERE/////////////////////////

                // PHONE's ANGLE WITHIN FIRST LAPTOP//
                if (angle1 != 0.0f) {
                    if (angle1 * 180 / Math.PI - 40.0 < fusedOrientation[0] * 180 / Math.PI
                            && fusedOrientation[0] * 180 / Math.PI < angle1 * 180 / Math.PI + 40.0) {
                        client1.runClient("left pressed");
                    }
                }
                //PHONE's ANGLE WITHIN SECOND LAPTOP//
                if (angle2 != 0.0f) {
                    if (angle2 * 180 / Math.PI - 40.0 < fusedOrientation[0] * 180 / Math.PI
                            && fusedOrientation[0] * 180 / Math.PI < angle2 * 180 / Math.PI + 40.0) {
                        client2.runClient("left pressed");
                    }
                }
                break;
            case MotionEvent.ACTION_MOVE:
                break;
            case MotionEvent.ACTION_UP:
                view.setImageResource(R.drawable.left_button);
                // PHONE's ANGLE WITHIN FIRST LAPTOP//
                if (angle1 != 0.0f) {
                    if (angle1 * 180 / Math.PI - 40.0f < fusedOrientation[0] * 180 / Math.PI
                            && fusedOrientation[0] * 180 / Math.PI < angle1 * 180 / Math.PI + 40.0f) {
                        client1.runClient("left released");
                    }
                }
                //PHONE's ANGLE WITHIN SECOND LAPTOP//
                if (angle2 != 0.0f) {
                    if (angle2 * 180 / Math.PI - 40.0f < fusedOrientation[0] * 180 / Math.PI
                            && fusedOrientation[0] * 180 / Math.PI < angle2 * 180 / Math.PI + 40.0f) {
                        client2.runClient("left released");
                    }
                }
                break;
            }
            return true;
        }
    });

    img_right.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            ImageView view = (ImageView) v;
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                view.setImageResource(R.drawable.right_button_press);
                // PHONE's ANGLE WITHIN FIRST LAPTOP//
                if (angle1 != 0.0f) {
                    if (angle1 * 180 / Math.PI - 40.0f < fusedOrientation[0] * 180 / Math.PI
                            && fusedOrientation[0] * 180 / Math.PI < angle1 * 180 / Math.PI + 40.0f) {
                        client1.runClient("right pressed");
                    }
                }
                //PHONE's ANGLE WITHIN SECOND LAPTOP//
                if (angle2 != 0.0f) {
                    if (angle2 * 180 / Math.PI - 40.0f < fusedOrientation[0] * 180 / Math.PI
                            && fusedOrientation[0] * 180 / Math.PI < angle2 * 180 / Math.PI + 40.0f) {
                        client2.runClient("right pressed");
                    }
                }
                break;
            case MotionEvent.ACTION_MOVE:
                break;
            case MotionEvent.ACTION_UP:
                view.setImageResource(R.drawable.right_button);
                break;
            }
            return true;
        }
    });

    img_up.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            ImageView view = (ImageView) v;
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                view.setImageResource(R.drawable.up_press);
                // PHONE's ANGLE WITHIN FIRST LAPTOP//
                if (angle1 != 0.0f) {
                    if (angle1 * 180 / Math.PI - 40.0f < fusedOrientation[0] * 180 / Math.PI
                            && fusedOrientation[0] * 180 / Math.PI < angle1 * 180 / Math.PI + 40.0f) {
                        client1.runClient("up pressed");
                    }
                }
                //PHONE's ANGLE WITHIN SECOND LAPTOP//
                if (angle2 != 0.0f) {
                    if (angle2 * 180 / Math.PI - 40.0f < fusedOrientation[0] * 180 / Math.PI
                            && fusedOrientation[0] * 180 / Math.PI < angle2 * 180 / Math.PI + 40.0f) {
                        client2.runClient("up pressed");
                    }
                }
                break;
            case MotionEvent.ACTION_MOVE:
                break;
            case MotionEvent.ACTION_UP:
                view.setImageResource(R.drawable.up);
                break;
            }
            return true;
        }
    });

    img_down.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            ImageView view = (ImageView) v;
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                view.setImageResource(R.drawable.down_press);
                // PHONE's ANGLE WITHIN FIRST LAPTOP//
                if (angle1 != 0.0f) {
                    if (angle1 * 180 / Math.PI - 40.0f < fusedOrientation[0] * 180 / Math.PI
                            && fusedOrientation[0] * 180 / Math.PI < angle1 * 180 / Math.PI + 40.0f) {
                        client1.runClient("down pressed");
                    }
                }
                //PHONE's ANGLE WITHIN SECOND LAPTOP//
                if (angle2 != 0.0f) {
                    if (angle2 * 180 / Math.PI - 40.0f < fusedOrientation[0] * 180 / Math.PI
                            && fusedOrientation[0] * 180 / Math.PI < angle2 * 180 / Math.PI + 40.0f) {
                        client2.runClient("down pressed");
                    }
                }
                break;
            case MotionEvent.ACTION_MOVE:
                break;
            case MotionEvent.ACTION_UP:
                view.setImageResource(R.drawable.down);
                break;
            }
            return true;
        }
    });
}

From source file:com.aapbd.utils.image.CacheImageDownloader.java

private void scaleImage1(ImageView view) {
    // Get the ImageView and its bitmap

    final Drawable drawing = view.getDrawable();
    if (drawing == null) {
        return; // Checking for null & return, as suggested in comments
    }// www. j  av  a  2s  .co m
    final Bitmap bitmap = ((BitmapDrawable) drawing).getBitmap();

    // Get current dimensions AND the desired bounding box
    int width = bitmap.getWidth();
    int height = bitmap.getHeight();
    final int bounding = dpToPx(view.getContext(), 300);
    Log.i("Test", "original width = " + Integer.toString(width));
    Log.i("Test", "original height = " + Integer.toString(height));
    Log.i("Test", "bounding = " + Integer.toString(bounding));

    // Determine how much to scale: the dimension requiring less scaling is
    // closer to the its side. This way the image always stays inside your
    // bounding box AND either x/y axis touches it.
    final float xScale = ((float) bounding) / width;
    final float yScale = ((float) bounding) / height;
    final float scale = (xScale <= yScale) ? xScale : yScale;
    Log.i("Test", "xScale = " + Float.toString(xScale));
    Log.i("Test", "yScale = " + Float.toString(yScale));
    Log.i("Test", "scale = " + Float.toString(scale));

    // Create a matrix for the scaling and add the scaling data
    final Matrix matrix = new Matrix();
    matrix.postScale(scale, scale);

    // Create a new bitmap and convert it to a format understood by the
    // ImageView
    final Bitmap scaledBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
    width = scaledBitmap.getWidth(); // re-use
    height = scaledBitmap.getHeight(); // re-use
    final BitmapDrawable result = new BitmapDrawable(scaledBitmap);
    Log.i("Test", "scaled width = " + Integer.toString(width));
    Log.i("Test", "scaled height = " + Integer.toString(height));

    // Apply the scaled bitmap
    view.setImageDrawable(result);

    // Now change ImageView's dimensions to match the scaled image
    final LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams();
    params.width = width;
    params.height = height;
    view.setLayoutParams(params);

    Log.i("Test", "done");
}

From source file:com.htc.dotdesign.ToolBoxService.java

private void setSelectedColor(ImageView button) {
    Drawable select = getResources().getDrawable(R.drawable.dot_design_select);
    select.setColorFilter(getResources().getColor(R.color.overlay_color), Mode.SRC_IN);

    ImageView selectedIcon = (ImageView) mPalette.findViewById(R.id.selected);
    selectedIcon.setBackground(select);/* ww w  . ja v  a 2  s . c  o m*/

    Resources res = getResources();
    int id = button.getId();
    int buttonLeft = button.getLeft();
    int buttonTop = button.getTop();
    int m1 = res.getDimensionPixelSize(R.dimen.margin_l);
    int m2 = res.getDimensionPixelSize(R.dimen.margin_m);
    int colorSize = res.getDimensionPixelSize(R.dimen.hv01);
    if (id == R.id.btn_color_11 || id == R.id.btn_color_12 || id == R.id.btn_color_13
            || id == R.id.btn_color_14) {
        buttonTop = m2;
    } else if (id == R.id.btn_color_21 || id == R.id.btn_color_22 || id == R.id.btn_color_23
            || id == R.id.btn_color_24) {
        buttonTop = m2 + colorSize + m1;
    } else {
        buttonTop = m2 + 2 * colorSize + 2 * m1;
    }

    if (id == R.id.btn_color_11 || id == R.id.btn_color_21 || id == R.id.btn_color_31) {
        buttonLeft = m2;
    } else if (id == R.id.btn_color_12 || id == R.id.btn_color_22 || id == R.id.btn_color_32) {
        buttonLeft = 3 * m2 + colorSize;
    } else if (id == R.id.btn_color_13 || id == R.id.btn_color_23 || id == R.id.btn_color_33) {
        buttonLeft = 5 * m2 + 2 * colorSize;
    } else {
        buttonLeft = 7 * m2 + 3 * colorSize;
    }

    int widthDiff = res.getDimensionPixelSize(R.dimen.select_color_width) - colorSize;
    int heightDiff = res.getDimensionPixelSize(R.dimen.select_color_height) - colorSize;
    int marginLeft = buttonLeft - (widthDiff / 2);
    int marginTop = buttonTop - (heightDiff / 2);

    RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) selectedIcon.getLayoutParams();
    params.setMargins(marginLeft, marginTop, 0, 0);
    selectedIcon.setLayoutParams(params);
    selectedIcon.setVisibility(View.VISIBLE);
}

From source file:com.android.tv.settings.dialog.DialogFragment.java

private void setContentView(View content) {
    TextView titleView = (TextView) content.findViewById(R.id.title);
    TextView breadcrumbView = (TextView) content.findViewById(R.id.breadcrumb);
    TextView descriptionView = (TextView) content.findViewById(R.id.description);
    titleView.setText(mTitle);//from w w  w . ja  va 2 s. c  o  m
    breadcrumbView.setText(mBreadcrumb);
    descriptionView.setText(mDescription);
    final ImageView iconImageView = (ImageView) content.findViewById(R.id.icon);
    if (mIconBackgroundColor != Color.TRANSPARENT) {
        iconImageView.setBackgroundColor(mIconBackgroundColor);
    }

    if (AccessibilityHelper.forceFocusableViews(getActivity())) {
        titleView.setFocusable(true);
        titleView.setFocusableInTouchMode(true);
        descriptionView.setFocusable(true);
        descriptionView.setFocusableInTouchMode(true);
        breadcrumbView.setFocusable(true);
        breadcrumbView.setFocusableInTouchMode(true);
    }

    if (mIconResourceId != 0) {
        iconImageView.setImageResource(mIconResourceId);
        updateViewSize(iconImageView);
    } else {
        if (mIconBitmap != null) {
            iconImageView.setImageBitmap(mIconBitmap);
            updateViewSize(iconImageView);
        } else {
            if (mIconUri != null) {
                iconImageView.setVisibility(View.INVISIBLE);

                DrawableDownloader bitmapDownloader = DrawableDownloader.getInstance(content.getContext());
                mBitmapCallBack = new BitmapCallback() {
                    @Override
                    public void onBitmapRetrieved(Drawable bitmap) {
                        if (bitmap != null) {
                            mIconBitmap = (bitmap instanceof BitmapDrawable)
                                    ? ((BitmapDrawable) bitmap).getBitmap()
                                    : null;
                            iconImageView.setVisibility(View.VISIBLE);
                            iconImageView.setImageDrawable(bitmap);
                            updateViewSize(iconImageView);
                        }
                    }
                };

                bitmapDownloader.getBitmap(new BitmapWorkerOptions.Builder(content.getContext())
                        .resource(mIconUri).width(iconImageView.getLayoutParams().width).build(),
                        mBitmapCallBack);
            } else {
                iconImageView.setVisibility(View.GONE);
            }
        }
    }

    content.setTag(R.id.title, titleView);
    content.setTag(R.id.breadcrumb, breadcrumbView);
    content.setTag(R.id.description, descriptionView);
    content.setTag(R.id.icon, iconImageView);
}

From source file:com.android.tv.settings.dialog.old.BaseDialogFragment.java

public void performEntryTransition(final Activity activity, final ViewGroup contentView, int iconResourceId,
        Uri iconResourceUri, final ImageView icon, final TextView title, final TextView description,
        final TextView breadcrumb) {
    // Pull out the root layout of the dialog and set the background drawable, to be
    // faded in during the transition.
    final ViewGroup twoPane = (ViewGroup) contentView.getChildAt(0);
    twoPane.setVisibility(View.INVISIBLE);

    // If the appropriate data is embedded in the intent and there is an icon specified
    // in the content fragment, we animate the icon from its initial position to the final
    // position. Otherwise, we perform a simpler transition in which the ActionFragment
    // slides in and the ContentFragment text fields slide in.
    mIntroAnimationInProgress = true;//  w  w  w .j  a  v  a  2s .c om
    List<TransitionImage> images = TransitionImage.readMultipleFromIntent(activity, activity.getIntent());
    TransitionImageAnimation ltransitionAnimation = null;
    final Uri iconUri;
    final int color;
    if (images != null && images.size() > 0) {
        if (iconResourceId != 0) {
            iconUri = Uri.parse(UriUtils.getAndroidResourceUri(activity, iconResourceId));
        } else if (iconResourceUri != null) {
            iconUri = iconResourceUri;
        } else {
            iconUri = null;
        }
        TransitionImage src = images.get(0);
        color = src.getBackground();
        if (iconUri != null) {
            ltransitionAnimation = new TransitionImageAnimation(contentView);
            ltransitionAnimation.addTransitionSource(src);
            ltransitionAnimation.transitionDurationMs(ANIMATE_IN_DURATION).transitionStartDelayMs(0)
                    .interpolator(new DecelerateInterpolator(1f));
        }
    } else {
        iconUri = null;
        color = 0;
    }
    final TransitionImageAnimation transitionAnimation = ltransitionAnimation;

    // Fade out the old activity, and hard cut the new activity.
    activity.overridePendingTransition(R.anim.hard_cut_in, R.anim.fade_out);

    int bgColor = mFragment.getResources().getColor(R.color.dialog_activity_background);
    mBgDrawable.setColor(bgColor);
    mBgDrawable.setAlpha(0);
    twoPane.setBackground(mBgDrawable);

    // If we're animating the icon, we create a new ImageView in which to place the embedded
    // bitmap. We place it in the root layout to match its location in the previous activity.
    mShadowLayer = (FrameLayoutWithShadows) twoPane.findViewById(R.id.shadow_layout);
    if (transitionAnimation != null) {
        transitionAnimation.listener(new TransitionImageAnimation.Listener() {
            @Override
            public void onRemovedView(TransitionImage src, TransitionImage dst) {
                if (icon != null) {
                    //want to make sure that users still see at least the source image
                    // if the dst image is too large to finish downloading before the
                    // animation is done. Check if the icon is not visible. This mean
                    // BaseContentFragement have not finish downloading the image yet.
                    if (icon.getVisibility() != View.VISIBLE) {
                        icon.setImageDrawable(src.getBitmap());
                        int intrinsicWidth = icon.getDrawable().getIntrinsicWidth();
                        LayoutParams lp = icon.getLayoutParams();
                        lp.height = lp.width * icon.getDrawable().getIntrinsicHeight() / intrinsicWidth;
                        icon.setVisibility(View.VISIBLE);
                    }
                    icon.setAlpha(1f);
                }
                if (mShadowLayer != null) {
                    mShadowLayer.setShadowsAlpha(1f);
                }
                onIntroAnimationFinished();
            }
        });
        icon.setAlpha(0f);
        if (mShadowLayer != null) {
            mShadowLayer.setShadowsAlpha(0f);
        }
    }

    // We need to defer the remainder of the animation preparation until the first
    // layout has occurred, as we don't yet know the final location of the icon.
    twoPane.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            twoPane.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            // if we buildLayer() at this time,  the texture is actually not created
            // delay a little so we can make sure all hardware layer is created before
            // animation, in that way we can avoid the jittering of start animation
            twoPane.postOnAnimationDelayed(mEntryAnimationRunnable, ANIMATE_DELAY);
        }

        final Runnable mEntryAnimationRunnable = new Runnable() {
            @Override
            public void run() {
                if (!mFragment.isAdded()) {
                    // We have been detached before this could run, so just bail
                    return;
                }

                twoPane.setVisibility(View.VISIBLE);
                final int secondaryDelay = SLIDE_IN_DISTANCE;

                // Fade in the activity background protection
                ObjectAnimator oa = ObjectAnimator.ofInt(mBgDrawable, "alpha", 255);
                oa.setDuration(ANIMATE_IN_DURATION);
                oa.setStartDelay(secondaryDelay);
                oa.setInterpolator(new DecelerateInterpolator(1.0f));
                oa.start();

                View actionFragmentView = activity.findViewById(mActionAreaId);
                boolean isRtl = ViewCompat.getLayoutDirection(contentView) == ViewCompat.LAYOUT_DIRECTION_RTL;
                int startDist = isRtl ? SLIDE_IN_DISTANCE : -SLIDE_IN_DISTANCE;
                int endDist = isRtl ? -actionFragmentView.getMeasuredWidth()
                        : actionFragmentView.getMeasuredWidth();

                // Fade in and slide in the ContentFragment TextViews from the start.
                prepareAndAnimateView(title, 0, startDist, secondaryDelay, ANIMATE_IN_DURATION,
                        new DecelerateInterpolator(1.0f), false);
                prepareAndAnimateView(breadcrumb, 0, startDist, secondaryDelay, ANIMATE_IN_DURATION,
                        new DecelerateInterpolator(1.0f), false);
                prepareAndAnimateView(description, 0, startDist, secondaryDelay, ANIMATE_IN_DURATION,
                        new DecelerateInterpolator(1.0f), false);

                // Fade in and slide in the ActionFragment from the end.
                prepareAndAnimateView(actionFragmentView, 0, endDist, secondaryDelay, ANIMATE_IN_DURATION,
                        new DecelerateInterpolator(1.0f), false);

                if (icon != null && transitionAnimation != null) {
                    // now we get the icon view in place,  update the transition target
                    TransitionImage target = new TransitionImage();
                    target.setUri(iconUri);
                    target.createFromImageView(icon);
                    if (icon.getBackground() instanceof ColorDrawable) {
                        ColorDrawable d = (ColorDrawable) icon.getBackground();
                        target.setBackground(d.getColor());
                    }
                    transitionAnimation.addTransitionTarget(target);
                    transitionAnimation.startTransition();
                } else if (icon != null) {
                    prepareAndAnimateView(icon, 0, startDist, secondaryDelay, ANIMATE_IN_DURATION,
                            new DecelerateInterpolator(1.0f), true /* is the icon */);
                    if (mShadowLayer != null) {
                        mShadowLayer.setShadowsAlpha(0f);
                    }
                }
            }
        };
    });
}

From source file:com.android.launcher3.Launcher.java

/**
 * Finds all the views we need and configure them properly.
 *///from   ww w .j  ava  2  s  .  com
private void setupViews() {
    mLauncherView = findViewById(R.id.launcher);
    mDragLayer = (DragLayer) findViewById(R.id.drag_layer);
    mFocusHandler = mDragLayer.getFocusIndicatorHelper();
    mWorkspace = (Workspace) mDragLayer.findViewById(R.id.workspace);
    mQsbContainer = mDragLayer.findViewById(
            mDeviceProfile.isVerticalBarLayout() ? R.id.workspace_blocked_row : R.id.qsb_container);
    mWorkspace.initParentViews(mDragLayer);

    mLauncherView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);

    // Setup the drag layer
    mDragLayer.setup(this, mDragController, mAllAppsController);

    // Setup the hotseat
    mHotseat = (Hotseat) findViewById(R.id.hotseat);
    if (mHotseat != null) {
        mHotseat.setOnLongClickListener(this);
    }

    // Setup the overview panel
    setupOverviewPanel();

    setuphome();

    // Setup the workspace
    mWorkspace.setHapticFeedbackEnabled(false);
    mWorkspace.setOnLongClickListener(this);
    mWorkspace.setup(mDragController);
    // Until the workspace is bound, ensure that we keep the wallpaper offset locked to the
    // default state, otherwise we will update to the wrong offsets in RTL
    mWorkspace.lockWallpaperToDefaultPage();
    mDragController.addDragListener(mWorkspace);

    // Get the search/delete/uninstall bar
    mDropTargetBar = (DropTargetBar) mDragLayer.findViewById(R.id.drop_target_bar);

    // Setup Apps and Widgets
    mAppsView = (AllAppsContainerView) findViewById(R.id.apps_view);
    mWidgetsView = (WidgetsContainerView) findViewById(R.id.widgets_view);
    if (mLauncherCallbacks != null && mLauncherCallbacks.getAllAppsSearchBarController() != null) {
        mAppsView.setSearchBarController(mLauncherCallbacks.getAllAppsSearchBarController());
    } else {
        mAppsView.setSearchBarController(new DefaultAppSearchController());
    }

    // Setup the drag controller (drop targets have to be added in reverse order in priority)
    mDragController.setDragScoller(mWorkspace);
    mDragController.setScrollView(mDragLayer);
    mDragController.setMoveTarget(mWorkspace);
    mDragController.addDropTarget(mWorkspace);
    mDropTargetBar.setup(mDragController);

    if (FeatureFlags.LAUNCHER3_ALL_APPS_PULL_UP) {
        mAllAppsController.setupViews(mAppsView, mHotseat, mWorkspace);
    }

    if (TestingUtils.MEMORY_DUMP_ENABLED) {
        TestingUtils.addWeightWatcher(this);
    }

    FrameLayout gBar = (FrameLayout) findViewById(R.id.g_bar);

    if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
        FrameLayout.LayoutParams gBarLayout = (FrameLayout.LayoutParams) gBar.getLayoutParams();
        gBarLayout.width = Utils.getScreenXDimension(this) - Utils.getScreenXDimension(this) / 6;
        gBar.setLayoutParams(gBarLayout);
    } else {
        FrameLayout.LayoutParams gBarLayout = (FrameLayout.LayoutParams) gBar.getLayoutParams();
        gBarLayout.width = Utils.getScreenYDimension(this) - Utils.getScreenYDimension(this) / 12;
        gBar.setLayoutParams(gBarLayout);
    }

    gBar.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            startSearch("", false, null, true);
        }
    });

    ImageView gSearch = (ImageView) findViewById(R.id.g_search);
    gSearch.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            startSearch("", false, null, true);
        }
    });

    FrameLayout.LayoutParams gSearchLayout = (FrameLayout.LayoutParams) gSearch.getLayoutParams();
    gSearchLayout.leftMargin = 30;
    gSearch.setLayoutParams(gSearchLayout);

    ImageView gSearchMic = (ImageView) findViewById(R.id.g_search_mic);
    if (IS_ALLOW_MIC) {
        gSearchMic.setVisibility(View.VISIBLE);
        gSearchMic.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
                startActivityForResult(intent, RECOGNIZER_REQ_CODE);
            }
        });
    } else {
        gSearchMic.setVisibility(View.GONE);
    }

    FrameLayout.LayoutParams gSearchMicLayout = (FrameLayout.LayoutParams) gSearchMic.getLayoutParams();
    gSearchMicLayout.rightMargin = 30;
    gSearchMic.setLayoutParams(gSearchMicLayout);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        if (Utilities.isAllowNightModePrefEnabled(getApplicationContext())) {
            gBar.setBackground(ContextCompat.getDrawable(getApplicationContext(), R.drawable.shape_night));
            gSearch.setImageDrawable(
                    ContextCompat.getDrawable(getApplicationContext(), R.drawable.g_icon_night));
            gSearch.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.night_color));
            gSearchMic
                    .setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.mic_night));
            gSearchMic.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.night_color));
        } else {
            gBar.setBackground(ContextCompat.getDrawable(getApplicationContext(), R.drawable.shape));
            gSearch.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.g_icon));
            gSearch.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), android.R.color.white));
            gSearchMic.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.mic));
            gSearchMic
                    .setBackgroundColor(ContextCompat.getColor(getApplicationContext(), android.R.color.white));
        }
    }

    if (!Utilities.isAllowPersisentSearchBarPrefEnabled(getApplicationContext())) {
        gBar.setVisibility(View.GONE);
        gSearch.setVisibility(View.GONE);
        gSearchMic.setVisibility(View.GONE);
    } else {
        gBar.setVisibility(View.VISIBLE);
        gSearch.setVisibility(View.VISIBLE);
        if (IS_ALLOW_MIC) {
            gSearchMic.setVisibility(View.VISIBLE);
        } else {
            gSearchMic.setVisibility(View.GONE);
        }
    }

}

From source file:de.anderdonau.spacetrader.Main.java

public boolean ExecuteAction(final Boolean CommanderFlees) {
    // *************************************************************************
    // A fight round
    // Return value indicates whether fight continues into another round
    // *************************************************************************
    Boolean CommanderGotHit, OpponentGotHit;
    long OpponentHull, ShipHull;
    int i;// w w w. j  a  va2 s. com
    int PrevEncounterType;
    Ship Ship = gameState.Ship;
    Ship Opponent = gameState.Opponent;
    Popup popup;

    CommanderGotHit = false;
    OpponentHull = Opponent.hull;
    ShipHull = Ship.hull;

    // Fire shots
    if (gameState.EncounterType == GameState.PIRATEATTACK || gameState.EncounterType == GameState.POLICEATTACK
            || gameState.EncounterType == GameState.TRADERATTACK
            || gameState.EncounterType == GameState.SPACEMONSTERATTACK
            || gameState.EncounterType == GameState.DRAGONFLYATTACK
            || gameState.EncounterType == GameState.POSTMARIEPOLICEENCOUNTER
            || gameState.EncounterType == GameState.SCARABATTACK
            || gameState.EncounterType == GameState.FAMOUSCAPATTACK) {
        CommanderGotHit = ExecuteAttack(Opponent, Ship, CommanderFlees, true);
    }

    OpponentGotHit = false;

    if (!CommanderFlees) {
        if (gameState.EncounterType == GameState.POLICEFLEE || gameState.EncounterType == GameState.TRADERFLEE
                || gameState.EncounterType == GameState.PIRATEFLEE) {
            OpponentGotHit = ExecuteAttack(Ship, Opponent, true, false);
        } else {
            OpponentGotHit = ExecuteAttack(Ship, Opponent, false, false);
        }
    }

    if (CommanderGotHit) {
        ((FragmentEncounter) currentFragment).playerShipNeedsUpdate = true;
        Bitmap tribble = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.tribble);
        ViewGroup container = (ViewGroup) findViewById(R.id.container);
        for (i = 0; i <= GameState.TRIBBLESONSCREEN; ++i) {
            int resID = mContext.getResources().getIdentifier("tribbleButton" + String.valueOf(i), "id",
                    mContext.getPackageName());
            ImageView imageView = (ImageView) container.findViewById(resID);
            if (imageView == null) {
                continue;
            }
            //noinspection ConstantConditions
            ViewGroup.MarginLayoutParams marginParams = new ViewGroup.MarginLayoutParams(
                    imageView.getLayoutParams());
            marginParams.setMargins(gameState.GetRandom(container.getWidth() - tribble.getWidth()),
                    gameState.GetRandom(container.getHeight() - tribble.getHeight()), 0, 0);
            RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(marginParams);
            imageView.setLayoutParams(layoutParams);
        }
    }
    if (OpponentGotHit) {
        ((FragmentEncounter) currentFragment).opponentShipNeedsUpdate = true;
    }

    // Determine whether someone gets destroyed
    if (Ship.hull <= 0 && Opponent.hull <= 0) {
        gameState.AutoAttack = false;
        gameState.AutoFlee = false;

        if (gameState.EscapePod) {
            EscapeWithPod();
        } else {
            popup = new Popup(this, "Both Destroyed",
                    "You and your opponent have managed to destroy each other.", "", "OK", cbShowNextPopup);
            popupQueue.push(popup);
            showNextPopup();
            btnDestroyed();
        }
        return false;
    } else if (Opponent.hull <= 0) {
        gameState.AutoAttack = false;
        gameState.AutoFlee = false;

        if (gameState.ENCOUNTERPIRATE(gameState.EncounterType) && Opponent.type != GameState.MANTISTYPE
                && gameState.PoliceRecordScore >= GameState.DUBIOUSSCORE) {
            popup = new Popup(this, "Bounty received",
                    String.format("You earned a bounty of %d cr.", GetBounty(Opponent)), "", "OK",
                    cbShowNextPopup);
            popupQueue.push(popup);
            showNextPopup();
        } else {
            popup = new Popup(this, "You win", "You have destroyed your opponent.", "", "OK", cbShowNextPopup);
            popupQueue.push(popup);
            showNextPopup();
        }
        if (gameState.ENCOUNTERPOLICE(gameState.EncounterType)) {
            ++gameState.PoliceKills;
            gameState.PoliceRecordScore += GameState.KILLPOLICESCORE;
        } else if (gameState.ENCOUNTERFAMOUS(gameState.EncounterType)) {
            if (gameState.ReputationScore < GameState.DANGEROUSREP) {
                gameState.ReputationScore = GameState.DANGEROUSREP;
            } else {
                gameState.ReputationScore += 100;
            }
            // bump news flag from attacked to ship destroyed
            gameState.replaceNewsEvent(gameState.latestNewsEvent(), gameState.latestNewsEvent() + 10);
        } else if (gameState.ENCOUNTERPIRATE(gameState.EncounterType)) {
            if (Opponent.type != GameState.MANTISTYPE) {
                gameState.Credits += GetBounty(Opponent);
                gameState.PoliceRecordScore += GameState.KILLPIRATESCORE;
                Scoop();
            }
            ++gameState.PirateKills;
        } else if (gameState.ENCOUNTERTRADER(gameState.EncounterType)) {
            ++gameState.TraderKills;
            gameState.PoliceRecordScore += GameState.KILLTRADERSCORE;
            Scoop();
        } else if (gameState.ENCOUNTERMONSTER(gameState.EncounterType)) {
            ++gameState.PirateKills;
            gameState.PoliceRecordScore += GameState.KILLPIRATESCORE;
            gameState.MonsterStatus = 2;
        } else if (gameState.ENCOUNTERDRAGONFLY(gameState.EncounterType)) {
            ++gameState.PirateKills;
            gameState.PoliceRecordScore += GameState.KILLPIRATESCORE;
            gameState.DragonflyStatus = 5;
        } else if (gameState.ENCOUNTERSCARAB(gameState.EncounterType)) {
            ++gameState.PirateKills;
            gameState.PoliceRecordScore += GameState.KILLPIRATESCORE;
            gameState.ScarabStatus = 2;
        }
        gameState.ReputationScore += 1 + (Opponent.type >> 1);
        return (false);
    } else if (Ship.hull <= 0) {
        gameState.AutoAttack = false;
        gameState.AutoFlee = false;

        if (gameState.EscapePod) {
            EscapeWithPod();
        } else {
            popup = new Popup(this, "You Lose", "Your ship has been destroyed by your opponent.", "", "OK",
                    cbShowNextPopup);
            popupQueue.push(popup);
            showNextPopup();
            btnDestroyed();
        }
        return (false);
    }

    // Determine whether someone gets away.
    if (CommanderFlees) {
        if (GameState.getDifficulty() == GameState.BEGINNER) {
            gameState.AutoAttack = false;
            gameState.AutoFlee = false;

            popup = new Popup(this, "Escaped", "You have managed to escape your opponent.",
                    "Just because this is Beginner level.", "OK", cbShowNextPopup);
            popupQueue.push(popup);
            showNextPopup();
            if (gameState.ENCOUNTERMONSTER(gameState.EncounterType)) {
                gameState.MonsterHull = Opponent.hull;
            }

            return (false);
        } else if ((gameState.GetRandom(7) + (Ship.PilotSkill() / 3))
                * 2 >= gameState.GetRandom(Opponent.PilotSkill()) * (2 + GameState.getDifficulty())) {
            gameState.AutoAttack = false;
            gameState.AutoFlee = false;
            if (CommanderGotHit) {
                popup = new Popup(this, "You Escaped", "You got hit, but still managed to escape.", "", "OK",
                        cbShowNextPopup);
                popupQueue.push(popup);
                showNextPopup();
            } else {
                popup = new Popup(this, "Escaped", "You have managed to escape your opponent.", "", "OK",
                        cbShowNextPopup);
                popupQueue.push(popup);
                showNextPopup();
            }
            if (gameState.ENCOUNTERMONSTER(gameState.EncounterType)) {
                gameState.MonsterHull = Opponent.hull;
            }

            return (false);
        }
    } else if (gameState.EncounterType == GameState.POLICEFLEE
            || gameState.EncounterType == GameState.TRADERFLEE
            || gameState.EncounterType == GameState.PIRATEFLEE
            || gameState.EncounterType == GameState.TRADERSURRENDER
            || gameState.EncounterType == GameState.PIRATESURRENDER) {
        if (gameState.GetRandom(Ship.PilotSkill()) * 4 <= gameState.GetRandom((7 + (Opponent.PilotSkill() / 3)))
                * 2) {
            gameState.AutoAttack = false;
            gameState.AutoFlee = false;
            popup = new Popup(this, "Opponent Escaped", "Your opponent has managed to escape.", "", "OK",
                    cbShowNextPopup);
            popupQueue.push(popup);
            showNextPopup();
            return (false);
        }
    }

    // Determine whether the opponent's actions must be changed
    PrevEncounterType = gameState.EncounterType;

    if (Opponent.hull < OpponentHull) {
        if (gameState.ENCOUNTERPOLICE(gameState.EncounterType)) {
            if (Opponent.hull < OpponentHull >> 1) {
                if (Ship.hull < ShipHull >> 1) {
                    if (gameState.GetRandom(10) > 5) {
                        gameState.EncounterType = GameState.POLICEFLEE;
                    }
                } else {
                    gameState.EncounterType = GameState.POLICEFLEE;
                }
            }
        } else if (gameState.EncounterType == GameState.POSTMARIEPOLICEENCOUNTER) {
            gameState.EncounterType = GameState.POLICEATTACK;
        } else if (gameState.ENCOUNTERPIRATE(gameState.EncounterType)) {
            if (Opponent.hull < (OpponentHull * 2) / 3) {
                if (Ship.hull < (ShipHull * 2) / 3) {
                    if (gameState.GetRandom(10) > 3) {
                        gameState.EncounterType = GameState.PIRATEFLEE;
                    }
                } else {
                    gameState.EncounterType = GameState.PIRATEFLEE;
                    if (gameState.GetRandom(10) > 8 && Opponent.type < GameState.MAXSHIPTYPE) {
                        gameState.EncounterType = GameState.PIRATESURRENDER;
                    }
                }
            }
        } else if (gameState.ENCOUNTERTRADER(gameState.EncounterType)) {
            if (Opponent.hull < (OpponentHull * 2) / 3) {
                if (gameState.GetRandom(10) > 3) {
                    gameState.EncounterType = GameState.TRADERSURRENDER;
                } else {
                    gameState.EncounterType = GameState.TRADERFLEE;
                }
            } else if (Opponent.hull < (OpponentHull * 9) / 10) {
                if (Ship.hull < (ShipHull * 2) / 3) {
                    // If you get damaged a lot, the trader tends to keep shooting
                    if (gameState.GetRandom(10) > 7) {
                        gameState.EncounterType = GameState.TRADERFLEE;
                    }
                } else if (Ship.hull < (ShipHull * 9) / 10) {
                    if (gameState.GetRandom(10) > 3) {
                        gameState.EncounterType = GameState.TRADERFLEE;
                    }
                } else {
                    gameState.EncounterType = GameState.TRADERFLEE;
                }
            }
        }
    }

    if (PrevEncounterType != gameState.EncounterType) {
        if (!(gameState.AutoAttack && (gameState.EncounterType == GameState.TRADERFLEE
                || gameState.EncounterType == GameState.PIRATEFLEE
                || gameState.EncounterType == GameState.POLICEFLEE))) {
            gameState.AutoAttack = false;
        }
        gameState.AutoFlee = false;
    }

    ((FragmentEncounter) currentFragment).playerShipNeedsUpdate = true;
    ((FragmentEncounter) currentFragment).opponentShipNeedsUpdate = true;

    ((FragmentEncounter) currentFragment).EncounterDisplayShips();
    ((FragmentEncounter) currentFragment).EncounterButtons();

    String buf = "The ";
    String buf2 = "";
    if (gameState.ENCOUNTERPOLICE(PrevEncounterType)) {
        buf2 = "police ship";
    } else if (gameState.ENCOUNTERPIRATE(PrevEncounterType)) {
        if (Opponent.type == GameState.MANTISTYPE) {
            buf2 = "alien ship";
        } else {
            buf2 = "pirate ship";
        }
    } else if (gameState.ENCOUNTERTRADER(PrevEncounterType)) {
        buf2 = "trader ship";
    } else if (gameState.ENCOUNTERMONSTER(PrevEncounterType)) {
        buf2 = "monster";
    } else if (gameState.ENCOUNTERDRAGONFLY(PrevEncounterType)) {
        buf2 = "Dragonfly";
    } else if (gameState.ENCOUNTERSCARAB(PrevEncounterType)) {
        buf2 = "Scarab";
    } else if (gameState.ENCOUNTERFAMOUS(PrevEncounterType)) {
        buf2 = "Captain";
    }

    buf += buf2;
    if (CommanderGotHit) {
        buf += " hits you.";
    } else if (!(PrevEncounterType == GameState.POLICEFLEE || PrevEncounterType == GameState.TRADERFLEE
            || PrevEncounterType == GameState.PIRATEFLEE)) {
        buf += " missed you.";
    } else {
        buf = "";
    }

    if (OpponentGotHit) {
        buf += "\nYou hit the " + buf2 + ".";
    }

    if (!CommanderFlees && !OpponentGotHit) {
        buf += "\n" + "You missed the " + buf2 + ".";
    }

    if (PrevEncounterType == GameState.POLICEFLEE || PrevEncounterType == GameState.TRADERFLEE
            || PrevEncounterType == GameState.PIRATEFLEE) {
        buf += "\nThe " + buf2 + " didn't get away.";
    }

    if (CommanderFlees) {
        buf += "\nThe " + buf2 + " is still following you.";
    }

    ((FragmentEncounter) currentFragment).EncounterDisplayNextAction(false);

    //noinspection ConstantConditions
    buf = ((FragmentEncounter) currentFragment).EncounterText.getText().toString() + "\n" + buf;
    ((FragmentEncounter) currentFragment).EncounterText.setText(buf);

    if (gameState.Continuous && (gameState.AutoAttack || gameState.AutoFlee)) {
        // Make sure there's always just one delayRunnable queued.
        // Otherwise several are queued if player keeps tapping Attack/Flee buttons.
        delayHandler.removeCallbacksAndMessages(null);
        gameState.CommanderFlees = CommanderFlees;
        delayHandler.postDelayed(delayRunnable, 1000);
    }
    return true;
}