Example usage for android.widget ImageView setLayoutParams

List of usage examples for android.widget ImageView setLayoutParams

Introduction

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

Prototype

public void setLayoutParams(ViewGroup.LayoutParams params) 

Source Link

Document

Set the layout parameters associated with this view.

Usage

From source file:com.xplink.android.carchecklist.CarCheckListActivity.java

/** Called when the activity is first created. */
@Override//from  w  ww  . j  a v a2 s  .com
public void onCreate(Bundle savedInstanceState) { // end 480
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    // deleteAllData();
    // ************************************************************************************
    listValue = restoreCheckList();
    if (listValue != null) {
        SharedPreferences restoreShared = getSharedPreferences("mysettings", Context.MODE_PRIVATE);
        Editor edit = restoreShared.edit();

        Map<String, Boolean> mapList = listValue.get(0);
        Map<String, Integer> mapSetting = listValue.get(1);
        int countChecknum = 0;
        int numPowerChecked = 0;
        int numEngineChecked = 0;
        int numExteriorChecked = 0;
        int numInteriorChecked = 0;
        int numDocumentChecked = 0;

        for (Map.Entry<String, Boolean> entry : mapList.entrySet()) {

            String[] tmp = entry.getKey().split("\\_");
            Log.i("checkkeyvalue", tmp[0] + " : " + tmp[1]);
            String key = tmp[0];

            if ("inside".equals(key)) {
                if (entry.getValue()) {
                    getTotalInterior(true);
                    numInteriorChecked++;
                    Log.i("checkbox", "numInteriorChecked : " + numInteriorChecked);
                }
            } else if ("power".equals(key)) {
                if (entry.getValue()) {
                    getTotalPower(true);
                    numPowerChecked++;
                    Log.i("checkbox", "numPowerChecked : " + numPowerChecked);
                }
            } else if ("engine".equals(key)) {
                if (entry.getValue()) {
                    getTotalEngine(true);
                    numEngineChecked++;
                    Log.i("checkbox", "numEngineChecked : " + numEngineChecked);
                }
            } else if ("outside".equals(key)) {
                if (entry.getValue()) {
                    getTotalExterior(true);
                    numExteriorChecked++;
                    Log.i("checkbox", "numExteriorChecked : " + numExteriorChecked);
                }
            } else if ("doc".equals(key)) {
                if (entry.getValue()) {
                    getTotalDocument(true);
                    numDocumentChecked++;
                    Log.i("checkbox", "numDocumentChecked : " + numDocumentChecked);
                }
            }
            edit.putBoolean(entry.getKey(), entry.getValue());
            // println(entry.getKey() + " : " + entry.getValue());
        }
        Checknum = countChecknum;

        edit.putInt("CheckPowerTotal", numPowerChecked);
        edit.putInt("CheckEngineTotal", numEngineChecked);
        edit.putInt("CheckExteriorTotal", numExteriorChecked);
        edit.putInt("CheckInteriorTotal", numInteriorChecked);
        edit.putInt("CheckDocumentTotal", numDocumentChecked);

        edit.commit();

        CheckPowerTotal = restoreShared.getInt("CheckPowerTotal", 0);
        CheckEngineTotal = restoreShared.getInt("CheckEngineTotal", 0);
        CheckExteriorTotal = restoreShared.getInt("CheckExteriorTotal", 0);
        CheckInteriorTotal = restoreShared.getInt("CheckInteriorTotal", 0);
        CheckDocumentTotal = restoreShared.getInt("CheckDocumentTotal", 0);

        Log.i("checklist", "in listValue - numPowerChecked : " + numPowerChecked);
        Log.i("checklist", "numEngineChecked : " + numEngineChecked);
        Log.i("checklist", "numExteriorChecked : " + numExteriorChecked);
        Log.i("checklist", "numInteriorChecked : " + numInteriorChecked);
        Log.i("checklist", "numDocumentChecked : " + numDocumentChecked);

        Log.i("checklist", "CheckPowerTotal : " + CheckPowerTotal);
        Log.i("checklist", "CheckEngineTotal : " + CheckEngineTotal);
        Log.i("checklist", "CheckExteriorTotal : " + CheckExteriorTotal);
        Log.i("checklist", "CheckInteriorTotal : " + CheckInteriorTotal);
        Log.i("checklist", "CheckDocumentTotal : " + CheckDocumentTotal);

        //edit.commit();
        for (Map.Entry<String, Integer> entry : mapSetting.entrySet()) {

            if ("interior".equals(entry.getKey())) {
                edit.putInt("Interiorbar", entry.getValue());
            } else if ("power".equals(entry.getKey())) {
                edit.putInt("Powerbar", entry.getValue());
            } else if ("engine".equals(entry.getKey())) {
                edit.putInt("Enginebar", entry.getValue());
            } else if ("exterior".equals(entry.getKey())) {
                edit.putInt("Exteriorbar", entry.getValue());
            } else {
                edit.putInt("Documentbar", entry.getValue());
            }
            // Log.i("checkSettingsName", "checkSettingsName : " +
            // entry.getKey());
        }
        edit.commit();

        /*
         * ProgressBar PowerProgress, EngineProgress, ExteriorProgress,
         * InteriorProgress, DocumentProgress, RatioProgress; TextView
         * percenpower, percenengine, percenexterior, perceninterior,
         * percendocument, Ratiotext;
         */
    }
    // ************************************************************************************
    // isSaveCheckBox();
    store = new Bundle();
    db = new DBCarCheckList(this);

    intent = new Intent(getApplicationContext(), RecordActivity.class);

    // getSettingShared();

    // Log.i("dbcarchecklist", "create object DBCarCheckList");

    DisplayMetrics metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);

    float height = metrics.heightPixels;
    float width = metrics.widthPixels;

    Log.d("height", "" + height);
    Log.d("width", "" + width);

    int left195 = (int) ((width / 100) * 15.3);
    int left200 = (int) ((width / 100) * 16.25);
    int leftt200 = (int) ((width / 100) * 17);
    int left230 = (int) ((width / 100) * 18);
    int left475 = (int) ((width / 100) * 37.1);
    int left480 = (int) ((width / 100) * 38);
    int left495 = (int) ((width / 100) * 38.7);
    int left500 = (int) ((width / 100) * 40.5);
    int left510 = (int) ((width / 100) * 39.7);
    int left530 = (int) ((width / 100) * 41.2);
    int left865 = (int) ((width / 100) * 67.6);
    int left870 = (int) ((width / 100) * 69.5);
    int leftt870 = (int) ((width / 100) * 68);
    int leftt900 = (int) ((width / 100) * 70);
    int left950 = (int) ((width / 100) * 75);
    int left1150 = (int) ((width / 100) * 93);
    int left1180 = (int) ((width / 100) * 92);

    int top10 = (int) ((height / 100) * 3);
    int top20 = (int) ((height / 100) * 6.5);
    int top40 = (int) ((height / 100) * 5);
    int top95 = (int) ((height / 100) * 12);
    int top100 = (int) ((height / 100) * 12.5);
    int top110 = (int) ((height / 100) * 16.5);
    int top130 = (int) ((height / 100) * 19);
    int top135 = (int) ((height / 100) * 17.5);
    int top225 = (int) ((height / 100) * 28.8);
    int top390 = (int) ((height / 100) * 53);
    int top410 = (int) ((height / 100) * 51.5);
    int top480 = (int) ((height / 100) * 64.5);
    int top500 = (int) ((height / 100) * 63);
    int top505 = (int) ((height / 100) * 63.8);
    int top595 = (int) ((height / 100) * 75);
    int top610 = (int) ((height / 100) * 76);

    Intent intent = getIntent();
    PercenPower = intent.getIntExtra("power", PercenPower);
    PercenEngine = intent.getIntExtra("engine", PercenEngine);
    PercenExterior = intent.getIntExtra("exterior", PercenExterior);
    PercenInterior = intent.getIntExtra("interior", PercenInterior);
    PercenDocument = intent.getIntExtra("document", PercenDocument);

    // follow : get data from shared preferences
    /*
     * SharedPreferences memo = getSharedPreferences("mysettings",
     * Context.MODE_PRIVATE); PercenPower = memo.getInt("PercenPower", 0);
     * PercenEngine = memo.getInt("PercenEngine", 0); PercenExterior =
     * memo.getInt("PercenExterior", 0); PercenInterior =
     * memo.getInt("PercenInterior", 0); PercenDocument =
     * memo.getInt("PercenDocument", 0);
     */

    CheckPowerTotal = intent.getIntExtra("numpower", CheckPowerTotal);
    CheckEngineTotal = intent.getIntExtra("numengine", CheckEngineTotal);
    CheckExteriorTotal = intent.getIntExtra("numexterior", CheckExteriorTotal);
    CheckInteriorTotal = intent.getIntExtra("numinterior", CheckInteriorTotal);
    CheckDocumentTotal = intent.getIntExtra("numdocument", CheckDocumentTotal);

    // Log.d("percen", "" + PercenPower);

    type = Typeface.createFromAsset(getAssets(), "Circular.ttf");

    MyCustomPanel view = new MyCustomPanel(this);

    ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(1200, 800);
    params.width = 1200;
    params.height = 800;

    addContentView(view, params);

    RelativeLayout.LayoutParams imgpower = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    imgpower.setMargins(left480, top20, 0, 0);
    RelativeLayout.LayoutParams bdpower = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    bdpower.setMargins(left475, top40, 0, 0);
    RelativeLayout.LayoutParams txtpower = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    txtpower.setMargins(left510, top135, 0, 0);

    ImageView borderpower = (ImageView) findViewById(R.id.powerborder);
    borderpower.setLayoutParams(bdpower);
    percenpower = (TextView) findViewById(R.id.percenpower);
    percenpower.setLayoutParams(txtpower);
    percenpower.setTypeface(type);
    percenpower.setText("" + PercenPower + "%");
    PowerProgress = (ProgressBar) findViewById(R.id.PowerProgressbar);
    PowerProgress.setMax(100);
    PowerProgress.setProgress(PercenPower);
    headpower = (ImageView) findViewById(R.id.headpower);
    btnPower = (ImageButton) findViewById(R.id.battery_button);
    btnPower.setLayoutParams(imgpower);
    btnPower.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {

            // startAnimation
            SlidePowerLayout();
        }
    });

    RelativeLayout.LayoutParams imgengine = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    imgengine.setMargins(left200, top110, 0, 0);
    RelativeLayout.LayoutParams bdengine = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    bdengine.setMargins(left195, top110, 0, 0);
    RelativeLayout.LayoutParams txtengine = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    txtengine.setMargins(left230, top225, 0, 0);

    ImageView borderengine = (ImageView) findViewById(R.id.engineborder);
    borderengine.setLayoutParams(bdengine);
    percenengine = (TextView) findViewById(R.id.percenengine);
    percenengine.setLayoutParams(txtengine);
    percenengine.setTypeface(type);
    percenengine.setText("" + PercenEngine + "%");
    EngineProgress = (ProgressBar) findViewById(R.id.EngineProgressbar);
    EngineProgress.setMax(100);
    EngineProgress.setProgress(PercenEngine);
    headengine = (ImageView) findViewById(R.id.headengine);
    btnEngine = (ImageButton) findViewById(R.id.engine_button);
    btnEngine.setLayoutParams(imgengine);
    btnEngine.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            // startAnimation
            SlideEngineLayout();
        }
    });

    RelativeLayout.LayoutParams imgexterior = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    imgexterior.setMargins(leftt200, top390, 0, 0);
    RelativeLayout.LayoutParams bdexterior = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    bdexterior.setMargins(left195, top410, 0, 0);
    RelativeLayout.LayoutParams txtexterior = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    txtexterior.setMargins(left230, top505, 0, 0);

    ImageView borderexterior = (ImageView) findViewById(R.id.exteriorborder);
    borderexterior.setLayoutParams(bdexterior);
    percenexterior = (TextView) findViewById(R.id.percenexterior);
    percenexterior.setLayoutParams(txtexterior);
    percenexterior.setTypeface(type);
    percenexterior.setText("" + PercenExterior + "%");
    ExteriorProgress = (ProgressBar) findViewById(R.id.ExteriorProgressbar);
    ExteriorProgress.setMax(100);
    ExteriorProgress.setProgress(PercenExterior);
    headexterior = (ImageView) findViewById(R.id.headexterior);
    btnExterior = (ImageButton) findViewById(R.id.outside_button);
    btnExterior.setLayoutParams(imgexterior);

    btnExterior.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            // startAnimation
            SlideExteriorLayout();
        }
    });

    RelativeLayout.LayoutParams imginterior = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    imginterior.setMargins(left500, top480, 0, 0);
    RelativeLayout.LayoutParams bdinterior = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    bdinterior.setMargins(left495, top500, 0, 0);
    RelativeLayout.LayoutParams txtinterior = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    txtinterior.setMargins(left530, top595, 0, 0);

    ImageView borderinterior = (ImageView) findViewById(R.id.interiorborder);
    borderinterior.setLayoutParams(bdinterior);
    perceninterior = (TextView) findViewById(R.id.perceninterior);
    perceninterior.setLayoutParams(txtinterior);
    perceninterior.setTypeface(type);
    perceninterior.setText("" + PercenInterior + "%");
    InteriorProgress = (ProgressBar) findViewById(R.id.InteriorProgressbar);
    InteriorProgress.setMax(100);
    InteriorProgress.setProgress(PercenInterior);
    headinterior = (ImageView) findViewById(R.id.headinterior);
    btnInterior = (ImageButton) findViewById(R.id.inside_button);
    btnInterior.setLayoutParams(imginterior);
    btnInterior.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            // startAnimation
            SlideInteriorLayout();
        }
    });

    RelativeLayout.LayoutParams imgdocument = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    imgdocument.setMargins(left870, top480, 0, 0);
    RelativeLayout.LayoutParams bddocument = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    bddocument.setMargins(left865, top500, 0, 0);
    RelativeLayout.LayoutParams txtdocument = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    txtdocument.setMargins(leftt900, top595, 0, 0);
    RelativeLayout.LayoutParams progdocument = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    progdocument.setMargins(leftt870, top610, 0, 0);

    ImageView borderdocument = (ImageView) findViewById(R.id.documentborder);
    borderdocument.setLayoutParams(bddocument);
    percendocument = (TextView) findViewById(R.id.percendocument);
    percendocument.setLayoutParams(txtdocument);
    percendocument.setTypeface(type);
    percendocument.setText("" + PercenDocument + "%");
    DocumentProgress = (ProgressBar) findViewById(R.id.DocumentProgressbar);
    DocumentProgress.setMax(100);
    DocumentProgress.setProgress(PercenDocument);
    headdocument = (ImageView) findViewById(R.id.headdocument);
    btnDocument = (ImageButton) findViewById(R.id.document_button);
    btnDocument.setLayoutParams(imgdocument);
    btnDocument.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            SlideDocumentLayout();

        }
    });

    RelativeLayout.LayoutParams imgsetting = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    imgsetting.setMargins(left1180, top10, 0, 0);
    RelativeLayout.LayoutParams txtratio = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    txtratio.setMargins(left950, top95, 0, 0);
    RelativeLayout.LayoutParams ratioprog = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    ratioprog.setMargins(left1150, top100, 0, 0);

    Ratiotext = (TextView) findViewById(R.id.ratiotext);
    Ratiotext.setLayoutParams(txtratio);
    RatioProgress = (ProgressBar) findViewById(R.id.ratio);
    RatioProgress.setLayoutParams(ratioprog);
    RatioProgress.setMax(100);
    headsetting = (ImageView) findViewById(R.id.headsetting);
    btnSetting = (ImageButton) findViewById(R.id.setting_button);
    btnSetting.setLayoutParams(imgsetting);
    btnSetting.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            SlideSettingLayout();

        }
    });

    // addMob
    LinearLayout layout = (LinearLayout) findViewById(R.id.admob);
    adView = new AdView(getApplicationContext());
    adView.setAdSize(AdSize.LEADERBOARD);
    adView.setAdUnitId(admonId);
    //adView.setAdUnitId("C17E5F3A146EC7E805175C72634D8098");
    // Add the adView to it
    layout.addView(adView);
    // Initiate a generic request to load it with an ad
    AdRequest.Builder adRequestBuilder = new AdRequest.Builder();
    adRequestBuilder.addTestDevice("C17E5F3A146EC7E805175C72634D8098");
    // adRequestBuilder.addTestDevice("9F5DF3C9768A51CB506B68902F766B40");
    adView.loadAd(adRequestBuilder.build());
    // adView.loadAd(new AdRequest.Builder().build());
    SharedPreferences shared = getSharedPreferences("mysettings", Context.MODE_PRIVATE);
    // Log.i("checksum",
    // "before call CheckRatio : " + shared.getInt("checknum", 0));
    CheckRatio();
    // Log.i("checklist", "checking percenpower : " +
    // shared.getInt("PercenPower", -1));

    // restoreProgressCheckList();
}

From source file:com.nttec.everychan.ui.presentation.BoardFragment.java

@SuppressLint("InlinedApi")
private void openGridGallery() {
    final int tnSize = resources.getDimensionPixelSize(R.dimen.post_thumbnail_size);

    class GridGalleryAdapter extends ArrayAdapter<Triple<AttachmentModel, String, String>>
            implements View.OnClickListener, AbsListView.OnScrollListener {
        private final GridView view;
        private boolean selectingMode = false;
        private boolean[] isSelected = null;
        private volatile boolean isBusy = false;

        public GridGalleryAdapter(GridView view, List<Triple<AttachmentModel, String, String>> list) {
            super(activity, 0, list);
            this.view = view;
            this.isSelected = new boolean[list.size()];
        }//from  w  w  w. j a  va2 s. co m

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        }

        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                if (isBusy)
                    setNonBusy();
                isBusy = false;
            } else
                isBusy = true;
        }

        private void setNonBusy() {
            if (!downloadThumbnails())
                return;
            for (int i = 0; i < view.getChildCount(); ++i) {
                View v = view.getChildAt(i);
                Object tnTag = v.findViewById(R.id.post_thumbnail_image).getTag();
                if (tnTag == null || tnTag == Boolean.FALSE)
                    fill(view.getPositionForView(v), v, false);
            }
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = new FrameLayout(activity);
                convertView.setLayoutParams(new AbsListView.LayoutParams(tnSize, tnSize));
                ImageView tnImage = new ImageView(activity);
                tnImage.setLayoutParams(new FrameLayout.LayoutParams(tnSize, tnSize, Gravity.CENTER));
                tnImage.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
                tnImage.setId(R.id.post_thumbnail_image);
                ((FrameLayout) convertView).addView(tnImage);
            }
            convertView.setTag(getItem(position).getLeft());
            safeRegisterForContextMenu(convertView);
            convertView.setOnClickListener(this);
            fill(position, convertView, isBusy);
            if (isSelected[position]) {
                /*ImageView overlay = new ImageView(activity);
                overlay.setImageResource(android.R.drawable.checkbox_on_background);*/
                FrameLayout overlay = new FrameLayout(activity);
                overlay.setBackgroundColor(Color.argb(128, 0, 255, 0));
                if (((FrameLayout) convertView).getChildCount() < 2)
                    ((FrameLayout) convertView).addView(overlay);

            } else {
                if (((FrameLayout) convertView).getChildCount() > 1)
                    ((FrameLayout) convertView).removeViewAt(1);
            }
            return convertView;
        }

        private void safeRegisterForContextMenu(View view) {
            try {
                view.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
                    @Override
                    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
                        if (presentationModel == null) {
                            Fragment currentFragment = MainApplication
                                    .getInstance().tabsSwitcher.currentFragment;
                            if (currentFragment instanceof BoardFragment) {
                                currentFragment.onCreateContextMenu(menu, v, menuInfo);
                            }
                        } else {
                            BoardFragment.this.onCreateContextMenu(menu, v, menuInfo);
                        }
                    }
                });
            } catch (Exception e) {
                Logger.e(TAG, e);
            }
        }

        @Override
        public void onClick(View v) {
            if (selectingMode) {
                int position = view.getPositionForView(v);
                isSelected[position] = !isSelected[position];
                notifyDataSetChanged();
            } else {
                BoardFragment fragment = BoardFragment.this;
                if (presentationModel == null) {
                    Fragment currentFragment = MainApplication.getInstance().tabsSwitcher.currentFragment;
                    if (currentFragment instanceof BoardFragment)
                        fragment = (BoardFragment) currentFragment;
                }
                fragment.openAttachment((AttachmentModel) v.getTag());
            }
        }

        private void fill(int position, View view, boolean isBusy) {
            AttachmentModel attachment = getItem(position).getLeft();
            String attachmentHash = getItem(position).getMiddle();
            ImageView tnImage = (ImageView) view.findViewById(R.id.post_thumbnail_image);
            if (attachment.thumbnail == null || attachment.thumbnail.length() == 0) {
                tnImage.setTag(Boolean.TRUE);
                tnImage.setImageResource(Attachments.getDefaultThumbnailResId(attachment.type));
                return;
            }
            tnImage.setTag(Boolean.FALSE);
            CancellableTask imagesDownloadTask = BoardFragment.this.imagesDownloadTask;
            ExecutorService imagesDownloadExecutor = BoardFragment.this.imagesDownloadExecutor;
            if (presentationModel == null) {
                Fragment currentFragment = MainApplication.getInstance().tabsSwitcher.currentFragment;
                if (currentFragment instanceof BoardFragment) {
                    imagesDownloadTask = ((BoardFragment) currentFragment).imagesDownloadTask;
                    imagesDownloadExecutor = ((BoardFragment) currentFragment).imagesDownloadExecutor;
                }
            }
            bitmapCache.asyncGet(attachmentHash, attachment.thumbnail, tnSize, chan, localFile,
                    imagesDownloadTask, tnImage, imagesDownloadExecutor, Async.UI_HANDLER,
                    downloadThumbnails() && !isBusy,
                    downloadThumbnails() ? (isBusy ? 0 : R.drawable.thumbnail_error)
                            : Attachments.getDefaultThumbnailResId(attachment.type));
        }

        public void setSelectingMode(boolean selectingMode) {
            this.selectingMode = selectingMode;
            if (!selectingMode) {
                Arrays.fill(isSelected, false);
                notifyDataSetChanged();
            }
        }

        public void selectAll() {
            if (selectingMode) {
                Arrays.fill(isSelected, true);
                notifyDataSetChanged();
            }
        }

        public void downloadSelected(final Runnable onFinish) {
            final Dialog progressDialog = ProgressDialog.show(activity,
                    resources.getString(R.string.grid_gallery_dlg_title),
                    resources.getString(R.string.grid_gallery_dlg_message), true, false);
            Async.runAsync(new Runnable() {
                @Override
                public void run() {
                    BoardFragment fragment = BoardFragment.this;
                    if (fragment.presentationModel == null) {
                        Fragment currentFragment = MainApplication.getInstance().tabsSwitcher.currentFragment;
                        if (currentFragment instanceof BoardFragment)
                            fragment = (BoardFragment) currentFragment;
                    }
                    boolean flag = false;
                    for (int i = 0; i < isSelected.length; ++i)
                        if (isSelected[i])
                            if (!fragment.downloadFile(getItem(i).getLeft(), true))
                                flag = true;
                    final boolean toast = flag;
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (toast)
                                Toast.makeText(activity, R.string.notification_download_exists_or_in_queue,
                                        Toast.LENGTH_LONG).show();
                            progressDialog.dismiss();
                            onFinish.run();
                        }
                    });
                }
            });
        }
    }

    try {
        List<Triple<AttachmentModel, String, String>> list = presentationModel.getAttachments();
        if (list == null) {
            Toast.makeText(activity, R.string.notifacation_updating_now, Toast.LENGTH_LONG).show();
            return;
        }

        GridView grid = new GridView(activity);
        final GridGalleryAdapter gridAdapter = new GridGalleryAdapter(grid, list);
        grid.setNumColumns(GridView.AUTO_FIT);
        grid.setColumnWidth(tnSize);
        int spacing = (int) (resources.getDisplayMetrics().density * 5 + 0.5f);
        grid.setVerticalSpacing(spacing);
        grid.setHorizontalSpacing(spacing);
        grid.setPadding(spacing, spacing, spacing, spacing);
        grid.setAdapter(gridAdapter);
        grid.setOnScrollListener(gridAdapter);
        grid.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f));

        final Button btnToSelecting = new Button(activity);
        btnToSelecting.setText(R.string.grid_gallery_select);
        CompatibilityUtils.setTextAppearance(btnToSelecting, android.R.style.TextAppearance_Small);
        btnToSelecting.setSingleLine();
        btnToSelecting.setVisibility(View.VISIBLE);
        btnToSelecting.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));

        final LinearLayout layoutSelectingButtons = new LinearLayout(activity);
        layoutSelectingButtons.setOrientation(LinearLayout.HORIZONTAL);
        layoutSelectingButtons.setWeightSum(10f);
        Button btnDownload = new Button(activity);
        btnDownload.setLayoutParams(
                new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 3.25f));
        btnDownload.setText(R.string.grid_gallery_download);
        CompatibilityUtils.setTextAppearance(btnDownload, android.R.style.TextAppearance_Small);
        btnDownload.setSingleLine();
        Button btnSelectAll = new Button(activity);
        btnSelectAll.setLayoutParams(
                new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 3.75f));
        btnSelectAll.setText(android.R.string.selectAll);
        CompatibilityUtils.setTextAppearance(btnSelectAll, android.R.style.TextAppearance_Small);
        btnSelectAll.setSingleLine();
        Button btnCancel = new Button(activity);
        btnCancel.setLayoutParams(new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 3f));
        btnCancel.setText(android.R.string.cancel);
        CompatibilityUtils.setTextAppearance(btnCancel, android.R.style.TextAppearance_Small);
        btnCancel.setSingleLine();
        layoutSelectingButtons.addView(btnDownload);
        layoutSelectingButtons.addView(btnSelectAll);
        layoutSelectingButtons.addView(btnCancel);
        layoutSelectingButtons.setVisibility(View.GONE);
        layoutSelectingButtons.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));

        btnToSelecting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                btnToSelecting.setVisibility(View.GONE);
                layoutSelectingButtons.setVisibility(View.VISIBLE);
                gridAdapter.setSelectingMode(true);
            }
        });

        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                btnToSelecting.setVisibility(View.VISIBLE);
                layoutSelectingButtons.setVisibility(View.GONE);
                gridAdapter.setSelectingMode(false);
            }
        });

        btnSelectAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                gridAdapter.selectAll();
            }
        });

        btnDownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                gridAdapter.downloadSelected(new Runnable() {
                    @Override
                    public void run() {
                        btnToSelecting.setVisibility(View.VISIBLE);
                        layoutSelectingButtons.setVisibility(View.GONE);
                        gridAdapter.setSelectingMode(false);
                    }
                });
            }
        });

        LinearLayout dlgLayout = new LinearLayout(activity);
        dlgLayout.setOrientation(LinearLayout.VERTICAL);
        dlgLayout.addView(btnToSelecting);
        dlgLayout.addView(layoutSelectingButtons);
        dlgLayout.addView(grid);

        Dialog gridDialog = new Dialog(activity);
        gridDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        gridDialog.setContentView(dlgLayout);
        gridDialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        gridDialog.show();
    } catch (OutOfMemoryError oom) {
        MainApplication.freeMemory();
        Logger.e(TAG, oom);
        Toast.makeText(activity, R.string.error_out_of_memory, Toast.LENGTH_LONG).show();
    }
}

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

/**
 * Finds all the views we need and configure them properly.
 *///from  w w  w.ja  va  2 s .c  o  m
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:self.philbrown.droidQuery.$.java

/**
 * Adds an Image over each selected View as a mask.
 * In most cases, this mask can be retrieved by querying siblings. For example:
 * <pre>//from   w  ww.  ja  v  a  2s.c o m
 * ImageView mask = (ImageView) $.with(myView).parent().selectChildren().selectImages().view(0);
 * </pre>
 * @param mask the bitmap to draw
 * @return this
 */
public $ mask(Bitmap mask) {
    for (View v : views) {
        ImageView image = new ImageView(context);
        image.setImageBitmap(mask);
        image.setScaleType(ScaleType.FIT_XY);
        ViewParent parent = v.getParent();
        if (parent != null && parent instanceof ViewGroup) {
            image.setLayoutParams(v.getLayoutParams());
            ((ViewGroup) parent).addView(image);
        } else if (v instanceof ViewGroup) {
            image.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT));
            ((ViewGroup) v).addView(image);
        }
    }
    return this;
}

From source file:self.philbrown.droidQuery.$.java

/**
 * Adds an Image over each selected View as a mask.
 * In most cases, this mask can be retrieved by querying siblings. For example:
 * <pre>// ww w . j a v a2s. c o m
 * ImageView mask = (ImageView) $.with(myView).parent().selectChildren().selectImages().view(0);
 * </pre>
 * @param mask the drawable to draw
 * @return this
 */
public $ mask(Drawable mask) {
    for (View v : views) {
        ImageView image = new ImageView(context);
        image.setImageDrawable(mask);
        image.setScaleType(ScaleType.FIT_XY);
        ViewParent parent = v.getParent();
        if (parent != null && parent instanceof ViewGroup) {
            image.setLayoutParams(v.getLayoutParams());
            ((ViewGroup) parent).addView(image);
        } else if (v instanceof ViewGroup) {
            image.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT));
            ((ViewGroup) v).addView(image);
        }
    }
    return this;
}

From source file:self.philbrown.droidQuery.$.java

/**
 * Adds an Image over each selected View as a mask. 
 * In most cases, this mask can be retrieved by querying siblings. For example:
 * <pre>/*from   w  w w  . ja  v  a  2s  .  c o  m*/
 * ImageView mask = (ImageView) $.with(myView).parent().selectChildren().selectImages().view(0);
 * </pre>
 * @param resourceId the resource ID of the mask drawable
 * @return this
 */
public $ mask(int resourceId) {
    for (View v : views) {
        ImageView image = new ImageView(context);
        image.setImageResource(resourceId);
        image.setScaleType(ScaleType.FIT_XY);
        ViewParent parent = v.getParent();
        if (parent != null && parent instanceof ViewGroup) {
            image.setLayoutParams(v.getLayoutParams());
            ((ViewGroup) parent).addView(image);
        } else if (v instanceof ViewGroup) {
            image.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT));
            ((ViewGroup) v).addView(image);
        }
    }
    return this;
}

From source file:self.philbrown.droidQuery.$.java

/**
 * Adds an Image over each selected View as a mask.
 * In most cases, this mask can be retrieved by querying siblings. For example:
 * <pre>//from  w  w w  .  j  a v  a2  s .  c o m
 * ImageView mask = (ImageView) $.with(myView).parent().selectChildren().selectImages().view(0);
 * </pre>
 * @param source asset path, file path (starting with "file://") or URL to image
 * @param width specifies the output bitmap width
 * @param height specifies the output bitmap height
 * @param error if the given source is a file or asset, this receives a droidQuery wrapping the 
 * current context and the {@code Throwable} error. Otherwise, this will receive an
 * Ajax error.
 * @return this
 * @see AjaxOptions#error(Function)
 */
public $ mask(String source, int width, int height, Function error) {
    if (source.startsWith("file://")) {
        try {
            BitmapFactory.Options opt = new BitmapFactory.Options();
            opt.inPreferredConfig = Bitmap.Config.ARGB_8888;
            if (width >= 0)
                opt.outWidth = width;
            if (height >= 0)
                opt.outHeight = height;
            Bitmap bitmap = BitmapFactory.decodeFile(source.substring(6), opt);
            for (View v : views) {
                ImageView image = new ImageView(context);
                image.setImageBitmap(Bitmap.createBitmap(bitmap));
                image.setScaleType(ScaleType.FIT_XY);
                ViewParent parent = v.getParent();
                if (parent != null && parent instanceof ViewGroup) {
                    image.setLayoutParams(v.getLayoutParams());
                    ((ViewGroup) parent).addView(image);
                } else if (v instanceof ViewGroup) {
                    image.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                            ViewGroup.LayoutParams.MATCH_PARENT));
                    ((ViewGroup) v).addView(image);
                }
            }
        } catch (Throwable t) {
            if (error != null) {
                error.invoke($.with(context), t);
            }
        }
    } else if (URLUtil.isValidUrl(source)) {
        AjaxOptions options = new AjaxOptions().url(source).type("GET").dataType("image").context(context)
                .global(false).success(new Function() {
                    @Override
                    public void invoke($ droidQuery, Object... params) {
                        Bitmap bitmap = (Bitmap) params[0];
                        for (View v : views) {
                            ImageView image = new ImageView(context);
                            image.setImageBitmap(Bitmap.createBitmap(bitmap));
                            image.setScaleType(ScaleType.FIT_XY);
                            ViewParent parent = v.getParent();
                            if (parent != null && parent instanceof ViewGroup) {
                                image.setLayoutParams(v.getLayoutParams());
                                ((ViewGroup) parent).addView(image);
                            } else if (v instanceof ViewGroup) {
                                image.setLayoutParams(
                                        new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                                                ViewGroup.LayoutParams.MATCH_PARENT));
                                ((ViewGroup) v).addView(image);
                            }
                        }
                    }
                });

        if (error != null) {
            options.error(error);
        }
        if (width >= 0) {
            options.imageWidth(width);
        }
        if (height >= 0) {
            options.imageHeight(height);
        }
        $.ajax(options);
    } else {
        try {
            BitmapFactory.Options opt = new BitmapFactory.Options();
            opt.inSampleSize = 1;
            opt.inPurgeable = true;
            opt.inInputShareable = false;
            if (width >= 0)
                opt.outWidth = width;
            if (height >= 0)
                opt.outHeight = height;
            Bitmap bitmap = BitmapFactory.decodeStream(context.getAssets().open(source), new Rect(0, 0, 0, 0),
                    opt);
            for (View v : views) {
                ImageView image = new ImageView(context);
                image.setImageBitmap(Bitmap.createBitmap(bitmap));
                image.setScaleType(ScaleType.FIT_XY);
                ViewParent parent = v.getParent();
                if (parent != null && parent instanceof ViewGroup) {
                    image.setLayoutParams(v.getLayoutParams());
                    ((ViewGroup) parent).addView(image);
                } else if (v instanceof ViewGroup) {
                    image.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                            ViewGroup.LayoutParams.MATCH_PARENT));
                    ((ViewGroup) v).addView(image);
                }
            }

        } catch (Throwable t) {
            if (error != null) {
                error.invoke($.with(context), t);
            }
        }

    }
    return this;
}

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;/*from ww w.jav  a 2  s .  co  m*/
    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;
}