You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Studio使用OnBarcode库生成Code128条码后如何显示?

Code128条码显示的两种实现方案

方案1:使用已写的自定义Test View直接渲染

你编写的内部Test类已经在onDraw方法中实现了条码绘制逻辑,只需要将该自定义View添加到Activity的视图层级即可显示,无需额外处理ImageView:

  • 在onCreate方法末尾添加如下代码即可生效:
// 实例化自定义条码View
Test barcodeView = new Test(this);
// 若要保留原有布局,可将该View添加到根布局中
ViewGroup rootLayout = findViewById(android.R.id.content);
rootLayout.addView(barcodeView);
// 若不需要原有布局,可直接setContentView(barcodeView)

方案2:生成Bitmap赋值给ImageView(更简洁)

你注释的imageView.setImageBitmap(barcode)写法错误,库支持直接生成条码Bitmap,无需自定义View,直接在onCreate中执行如下逻辑即可:

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

    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);
    try {
        // 调用生成Bitmap方法,传入自定义宽高即可
        Bitmap barcodeBitmap = barcode.drawBarcode(300, 150);
        imageView.setImageBitmap(barcodeBitmap);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

选用方案2的话,可以直接删除内部Test类的冗余代码。


内容的提问来源于stack exchange,提问作者sidek22

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 14:24:03