0

I am trying to execute the Code128 tutorial according to this website: http://www.onbarcode.com/products/android_barcode/barcodes/code_128.html, but I have no idea how to display the barcode.

Here is the Java code:

public class MainActivity extends AppCompatActivity {
private ImageView imageView;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    imageView = findViewById(R.id.imageView2);

    class Test extends View {

        public Test(Context context) {
            super(context);
        }

        @Override
        protected void onDraw(Canvas canvas) {
            Code128 barcode = new Code128();
            barcode.setData("112233445566");     
            barcode.setProcessTilde(false);
            barcode.setUom(IBarcode.UOM_PIXEL);
            barcode.setX(1f);
            barcode.setY(75f);
            barcode.setLeftMargin(10f);
            barcode.setRightMargin(10f);
            barcode.setTopMargin(10f);
            barcode.setBottomMargin(10f);
            barcode.setResolution(72);
            barcode.setShowText(true);
            barcode.setTextFont(new AndroidFont("Arial", Typeface.NORMAL, 12));
            barcode.setTextMargin(6);
            barcode.setTextColor(AndroidColor.black);
            barcode.setForeColor(AndroidColor.black);
            barcode.setBackColor(AndroidColor.white);
            RectF bounds = new RectF(30, 30, 0, 120);

            try {
                barcode.drawBarcode(canvas, bounds);
             //   imageView.setImageBitmap(barcode);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }
}

What method should I use to display the barcode?

sidek22
  • 1
  • 1

1 Answers1

0

1)Make that inner view class its own separate class in its own file.

2)Give it all 3 required constructors, not just the one.

3)Add that view to your layout somewhere.

That should be enough. Although if you wanted a true BarcodeView class, you obviously would want to add a setBarcode function that takes a Code128 as a parameter, saves it internally, invalidates the view, and have the onDraw use that barcode function.

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
  • Hey bro, Can You help me writing the code for it? I only need to display the barcode, I'll make the seperate class in the file etc. later but I just need to display the code for now. – sidek22 Oct 25 '21 at 18:50
  • I do not understand the 3 constructors part. Please help bro – sidek22 Oct 25 '21 at 18:52
  • Views have 3 constructors. You only implemented one. That one only works if you are programmatically creating the View and adding it to your root view somehow. If you want to access it via xml, you need to add the other two. Also, it needs to be a static inner class if you keep it an inner class. – Gabe Sechan Oct 25 '21 at 18:54