单击按钮之间单击以初始化2个模型

时间:2018-06-17 13:36:07

标签: java android

我想在两个按钮之间分开点击,当按下按钮1时,初始化model1,第一个模型的分割将显示在屏幕上,而button2和model2的分割相同 问题是:2个模型没有分开,因为当点击两个按钮中的任何一个时,两个模型同时出现。

这是(MainSecond.java),我初始化了2个按钮:

public class MainSecond extends Activity {
    public Button button1;
    public Button button2;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second_main);


        button1 = (Button) findViewById(R.id.button1);
        button1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Toast.makeText(MainSecond.this,"b1c",Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(MainSecond.this, MainActivity.class);
                    intent.putExtra("message","hello");
                    startActivity(intent);

                }
            });

        button2 = (Button) findViewById(R.id.button2);
        button2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {


                    Intent intent = new Intent(MainSecond.this, MainActivity.class);
                    intent.putExtra("message","hi");
                    startActivity(intent);

                }

            });
    }
}

这是我的MainActivity.java,我点击2个按钮并初始化2个模型:

public void onCreate (Bundle savedInstanceState){
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    buckyButton = findViewById(R.id.buckysButton);


    //  src_img =(ImageView) findViewById(R.id.src_img) ;

    Intent intent=getIntent();
    // int intval=intent.getIntExtra("name",0);
    String message=intent.getStringExtra("message");


    if(message=="hello"){

        initModel();

    }

    else if(message=="hi"){

        initModel2();
    }
}

private void initModel() {
    new InitializeModelAsyncTask().execute((Void)null);
}
private void initModel2() {
    new InitializeModelAsyncTask2().execute((Void)null);
}

public class InitializeModelAsyncTask extends AsyncTask<Void, Void, Boolean> {


    @Override
    protected Boolean doInBackground(Void... voids) {
        final boolean ret = DeeplabModel.initialize();
        Logger.debug("initialize deeplab model: %s", ret);

        return ret;

    }
}

public class InitializeModelAsyncTask2 extends AsyncTask<Void, Void, Boolean> {


    @Override
    protected Boolean doInBackground(Void... voids) {
        final boolean ret2 = DeeplabModel2.initialize();
        Logger.debug("initialize deeplab model: %s", ret2);

    }
}

这是最重要的代码,负责在屏幕上显示模型:

SegmentBitmapsLoader.java

public class SegmentBitmapsLoader extends AbsAsyncDataLoader<List<SegmentBitmap>> {

    private Uri mImageUri;


    public SegmentBitmapsLoader(Context context, Uri imageUri) {
        super(context);

        mImageUri = imageUri;

    }


    @Nullable
    @Override

    public List<SegmentBitmap> loadInBackground() {
        final Context context = getContext();

        if (context == null) {
            return null;
        }

        final Resources res = context.getResources();

        if (res == null) {
            return null;
        }

        if (mImageUri == null) {
            return null;
        }

        final String filePath = FilePickUtils.getPath(context, mImageUri);
        Logger.debug("file to mask: %s", filePath);
        if (TextUtils.isEmpty(filePath)) {
            return null;
        }

        boolean vertical = checkAndReportDimen(filePath);

        final int dw = res.getDimensionPixelSize(
                                                 vertical ? R.dimen.image_width_v : R.dimen.image_width_h);
        final int dh = res.getDimensionPixelSize(
                                                 vertical ? R.dimen.image_height_v : R.dimen.image_height_h);
        Logger.debug("display image dimen: [%d x %d]", dw, dh);

        Bitmap bitmap = decodeBitmapFromFile(filePath, dw, dh);
        if (bitmap == null) {
            return null;
        }


        List<SegmentBitmap> bitmaps = new ArrayList<>();

        bitmaps.add(new SegmentBitmap(R.string.label_original, bitmap));//important note

        final int w = bitmap.getWidth();
        final int h = bitmap.getHeight();
        Logger.debug("decoded file dimen: [%d x %d]", w, h);

        EventBus.getDefault().post(new ImageDimenEvent(mImageUri, w, h));

        if (DeeplabModel2.initialize()==true) {


            float resizeRatio = (float) DeeplabModel2.INPUT_SIZE / Math.max(bitmap.getWidth(), bitmap.getHeight());
            int rw = Math.round(w * resizeRatio);
            int rh = Math.round(h * resizeRatio);
            Logger.debug("resize bitmap: ratio = %f, [%d x %d] -> [%d x %d]",
                         resizeRatio, w, h, rw, rh);
            Bitmap resized = ImageUtils.tfResizeBilinear(bitmap, rw, rh);
            Bitmap mask = DeeplabModel2.segment(resized);
            if (mask != null) {
                mask = BitmapUtils.scaleBitmap(mask, w, h);
                bitmaps.add(new SegmentBitmap(R.string.label_mask, mask));

                final Bitmap cropped = cropBitmapWithMask(bitmap, mask);
                bitmaps.add(new SegmentBitmap(R.string.label_cropped, cropped));
            } else {
                bitmaps.add(new SegmentBitmap(R.string.label_mask, (Bitmap) null));
                bitmaps.add(new SegmentBitmap(R.string.label_cropped, (Bitmap) null));

            }


        }



        else if (DeeplabModel.initialize()==true) {


            float resizeRatio = (float) DeeplabModel.INPUT_SIZE / Math.max(bitmap.getWidth(), bitmap.getHeight());
            int rw = Math.round(w * resizeRatio);
            int rh = Math.round(h * resizeRatio);
            Logger.debug("resize bitmap: ratio = %f, [%d x %d] -> [%d x %d]",
                         resizeRatio, w, h, rw, rh);
            Bitmap resized = ImageUtils.tfResizeBilinear(bitmap, rw, rh);
            Bitmap mask = DeeplabModel.segment(resized);
            if (mask != null) {
                mask = BitmapUtils.scaleBitmap(mask, w, h);
                bitmaps.add(new SegmentBitmap(R.string.label_mask, mask));

                final Bitmap cropped = cropBitmapWithMask(bitmap, mask);
                bitmaps.add(new SegmentBitmap(R.string.label_cropped, cropped));
            } else {
                bitmaps.add(new SegmentBitmap(R.string.label_mask, (Bitmap) null));
                bitmaps.add(new SegmentBitmap(R.string.label_cropped, (Bitmap) null));

            }


        }

        return bitmaps;
    }


    private boolean checkAndReportDimen(String filePath) {
        if (TextUtils.isEmpty(filePath)) {
            return false;
        }

        // First decode with inJustDecodeBounds=true to check dimensions
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);

        final int width = options.outWidth;
        final int height = options.outHeight;
        Logger.debug("original image dimen: %d x %d", width, height);

        EventBus.getDefault().post(new ImageDimenEvent(mImageUri, width, height));

        return (height > width);
    }


    private Bitmap cropBitmapWithMask(Bitmap original, Bitmap mask) {
        if (original == null
            || mask == null) {
            return null;
        }

        final int w = original.getWidth();
        final int h = original.getHeight();
        if (w <= 0 || h <= 0) {
            return null;
        }

        Bitmap cropped = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);


        Canvas canvas = new Canvas(cropped);
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);

        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
        canvas.drawBitmap(original, 0, 0, null);
        canvas.drawBitmap(mask, 0, 0, paint);
        paint.setXfermode(null);

        return cropped;
    }

    public static Bitmap decodeBitmapFromFile(String filePath,
                                              int reqWidth,
                                              int reqHeight) {
        if (TextUtils.isEmpty(filePath)) {
            return null;
        }

        // First decode with inJustDecodeBounds=true to check dimensions
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(filePath, options);
    }

    public static int calculateInSampleSize(
                                            BitmapFactory.Options options, int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {

            final int halfHeight = height / 2;
            final int halfWidth = width / 2;

            // Calculate the largest inSampleSize value that is a power of 2 and keeps both
            // height and width larger than the requested height and width.
            while ((halfHeight / inSampleSize) >= reqHeight
                   && (halfWidth / inSampleSize) >= reqWidth) {
                inSampleSize *= 2;
            }
        }

        return inSampleSize;
    }
}

1 个答案:

答案 0 :(得分:0)

我建议你看看设计模式。 你试图使用抽象工厂模式(https://en.wikipedia.org/wiki/Abstract_factory_pattern)来实现id。

以下是一个快速示例:

abstract interface IModelAsyncTask {
    public void action1();
    public void action2();
}

并且实现如下:

// ModelAsyncTask1
public class ModelAsyncTask1 implements IModelAsyncTask {
    @override
    public void action1() {
         // Logic here
    }
    public void action2() {
         // Logic here
    }
}

// ModelAsyncTask2
public class ModelAsyncTask2 implements IModelAsyncTask {
    @override
    public void action1() {
         // Logic here
    }
    public void action2() {
         // Logic here
    }
}

并在您的活动中,只需初始化:

IModelAsyncTask mAsyncTask;
if (condition1){
    mAsyncTask = ModelAsyncTask1();
} else if (condition2) {
   mAsyncTask = ModelAsyncTask2();
} else {
   // Throw exception 
}

mAsyncTask.action1();
相关问题