android 二维码制作,显示到UI,并保存SD卡,拿来就能用!!

简介:

转载请注明出处:王亟亟的大牛之路

现在二维码已经渗透了我们的生活,各种扫码关注啊,扫码下载的,今天上一个根据输入内容生成二维码的功能。

包结构:
这里写图片描述
界面截图:
这里写图片描述

这里写图片描述

功能:输入网址–>生成图片–>显示到Imageview–>储存到本地SD卡中

MainActivity(重要的部分已详细标注,生成的图片也经过测试可用)

public class MainActivity extends Activity {
    ImageView imageview;
    EditText webInput;
    Button MakeImage;
    Bitmap qrImage;
    private  ProgressDialog mLoadingDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        webInput=(EditText)findViewById(R.id.webInput);
        imageview=(ImageView)findViewById(R.id.imageview);
        MakeImage=(Button)findViewById(R.id.MakeImage);
        //业务逻辑
        doBusiness();
    }

    public void doBusiness(){
        MakeImage.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //判断是否有输入内容
                if(webInput.getText().toString().equals("")||webInput==null){
                    Toast.makeText(MainActivity.this, "请输入网址", Toast.LENGTH_SHORT).show();
                    return;
                }else{
                    showLoadingDialog("Loading...");
                    //回收bitmap
                        if(null != qrImage && !qrImage.isRecycled()){
                            qrImage.recycle();
                            qrImage = null;
                        }
                          try {
                            qrImage = makeQRImage(webInput.getText().toString(), 600, 600);
                        } catch (WriterException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                          imageview.setImageBitmap(qrImage);
                            //生成图片
                            if(isMountedSDCard()){
                                String filePath =Environment.getExternalStorageDirectory()+ "/MyLive/QRImage/"+"aa"+".jpg";
                                try {
                                    //保存图片
                                    saveAsJPEG(qrImage, filePath);
                                } catch (IOException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                                dismissLoadingDialog();
                                Toast.makeText(MainActivity.this, "保存成功", Toast.LENGTH_LONG).show();
                            }else{
                                Toast.makeText(MainActivity.this, "没有安装SD卡", Toast.LENGTH_LONG).show();
                            }


                }
            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    /*显示对话框*/
    public void showLoadingDialog(String msg) {
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            return;
        }
        mLoadingDialog = new ProgressDialog(this);
        mLoadingDialog.setMessage(msg);
        // mLoadingDialog.setOnKeyListener(mOnKeyListener);
        // mLoadingDialog.setCancelable(false);
        mLoadingDialog.show();
    }

    /**
     * 取消加载对话框
     */
    public void dismissLoadingDialog() {
        if (mLoadingDialog != null) {
            mLoadingDialog.dismiss();
        }
    }

    /**
     * 根据指定内容生成自定义宽高的二维码图片 
     * @param content 需要生成二维码的内容
     * @param width 二维码宽度
     * @param height 二维码高度
     * @throws WriterException 生成二维码异常
     */
    public static Bitmap makeQRImage(String content, int width, int height)
            throws WriterException {
        // 判断URL合法性
        if (!isNoBlankAndNoNull(content))
            return null;

        Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        // 图像数据转换,使用了矩阵转换
        BitMatrix bitMatrix = new QRCodeWriter().encode(content,
                BarcodeFormat.QR_CODE, width, height, hints);
        int[] pixels = new int[width * height];
        // 按照二维码的算法,逐个生成二维码的图片,两个for循环是图片横列扫描的结果
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                if (bitMatrix.get(x, y))
                    pixels[y * width + x] = 0xff000000;
                else
                    pixels[y * width + x] = 0xffffffff;
            }
        }
        // 生成二维码图片的格式,使用ARGB_8888
        Bitmap bitmap = Bitmap.createBitmap(width, height,
                Bitmap.Config.ARGB_8888);
        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);

        return bitmap;
    }

    /**
     * 判断字符串是否非空非null
     * @param strParm 需要判断的字符串
     * @return 真假
     */
    public static boolean isNoBlankAndNoNull(String strParm)
    {
      return ! ( (strParm == null) || (strParm.equals("")));
    }

    /**
     * 指定目录写入文件内容
     * @param filePath 文件路径+文件名
     * @param content 文件内容
     * @throws IOException
     */
    public static void saveAsJPEG(Bitmap bitmap,String filePath)
            throws IOException {
        FileOutputStream fos = null;

        try {
            File file = new File(filePath);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100,fos);
            fos.flush();
        } finally {
            if (fos != null) {
                fos.close();
            }
        }
    }

    public static boolean isMountedSDCard() {
        if (Environment.MEDIA_MOUNTED.equals(Environment
                .getExternalStorageState())) {
            return true;
        } else {
            return false;
        }
    }
}

布局文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.qrcodedemo.MainActivity" >

    <ScrollView
        android:id="@+id/scrollView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentTop="true" >
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" >
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal" >
                  <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignBottom="@+id/webInput"
                android:layout_alignParentLeft="true"
                android:layout_alignTop="@+id/webInput"
                android:text="输入网址:" 
                android:textSize="16sp"
                android:gravity="bottom"/>

               <EditText
                   android:id="@+id/webInput"
                   android:layout_width="wrap_content"
                   android:layout_height="wrap_content"
                   android:layout_alignParentTop="true"
                   android:layout_toRightOf="@+id/textView1"
                   android:ems="10" >
                   <requestFocus />
               </EditText>

        </LinearLayout>

            <Button
            android:id="@+id/MakeImage"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="MakeImage" />
            <ImageView
            android:id="@+id/imageview"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"/>

        </LinearLayout>
    </ScrollView>
</RelativeLayout>

源码地址:http://yunpan.cn/cd8sknyybpZzE 访问密码 8f62
因为在代码中已经注明,所以下源码看了用即可,不做过多解释用到的JAR包也在源码内

目录
相关文章
|
17天前
|
存储 消息中间件 人工智能
【04】AI辅助编程完整的安卓二次商业实战-寻找修改替换新UI首页图标-菜单图标-消息列表图标-优雅草伊凡
【04】AI辅助编程完整的安卓二次商业实战-寻找修改替换新UI首页图标-菜单图标-消息列表图标-优雅草伊凡
50 4
|
5月前
|
Java Android开发 开发者
Android使用zxing生成二维码
这是一篇关于如何在Android应用中生成二维码的教程。首先,需要导入zxing库的jar包。布局文件中包含一个按钮、一个图片控件和一个输入框。用户可以在输入框中输入想要转换为二维码的内容,点击按钮后,程序会通过实例化QRCodeWriter类并使用for循环绘制二维码图像,最后将生成的二维码显示在ImageView上。源码展示了具体的实现细节,包括布局定义与Java逻辑代码,便于开发者理解和实践。
106 2
|
11月前
|
搜索推荐 Android开发 开发者
探索安卓开发中的自定义视图:打造个性化UI组件
【10月更文挑战第39天】在安卓开发的世界中,自定义视图是实现独特界面设计的关键。本文将引导你理解自定义视图的概念、创建流程,以及如何通过它们增强应用的用户体验。我们将从基础出发,逐步深入,最终让你能够自信地设计和实现专属的UI组件。
|
10月前
|
XML 搜索推荐 前端开发
安卓开发中的自定义视图:打造个性化UI组件
在安卓应用开发中,自定义视图是一种强大的工具,它允许开发者创造独一无二的用户界面元素,从而提升应用的外观和用户体验。本文将通过一个简单的自定义视图示例,引导你了解如何在安卓项目中实现自定义组件,并探讨其背后的技术原理。我们将从基础的View类讲起,逐步深入到绘图、事件处理以及性能优化等方面。无论你是初学者还是有经验的开发者,这篇文章都将为你提供有价值的见解和技巧。
|
11月前
|
XML 前端开发 Android开发
Android:UI:Drawable:View/ImageView与Drawable
通过本文的介绍,我们详细探讨了Android中Drawable、View和ImageView的使用方法及其相互关系。Drawable作为图像和图形的抽象表示,提供了丰富的子类和自定义能力,使得开发者能够灵活地实现各种UI效果。View和ImageView则通过使用Drawable实现了各种图像和图形的显示需求。希望本文能为您在Android开发中使用Drawable提供有价值的参考和指导。
241 2
|
XML Android开发 UED
💥Android UI设计新风尚!掌握Material Design精髓,让你的界面颜值爆表!🎨
随着移动应用市场的蓬勃发展,用户对界面设计的要求日益提高。为此,掌握由Google推出的Material Design设计语言成为提升应用颜值和用户体验的关键。本文将带你深入了解Material Design的核心原则,如真实感、统一性和创新性,并通过丰富的组件库及示例代码,助你轻松打造美观且一致的应用界面。无论是色彩搭配还是动画效果,Material Design都能为你的Android应用增添无限魅力。
288 1
|
存储 搜索推荐 Java
探索安卓开发中的自定义视图:打造个性化UI组件Java中的异常处理:从基础到高级
【8月更文挑战第29天】在安卓应用的海洋中,一个独特的用户界面(UI)能让应用脱颖而出。自定义视图是实现这一目标的强大工具。本文将通过一个简单的自定义计数器视图示例,展示如何从零开始创建一个具有独特风格和功能的安卓UI组件,并讨论在此过程中涉及的设计原则、性能优化和兼容性问题。准备好让你的应用与众不同了吗?让我们开始吧!
|
编解码 Android开发
【Android Studio】使用UI工具绘制,ConstraintLayout 限制性布局,快速上手
本文介绍了Android Studio中使用ConstraintLayout布局的方法,通过创建布局文件、设置控件约束等步骤,快速上手UI设计,并提供了一个TV Launcher界面布局的绘制示例。
306 1
|
API Android开发
Android项目架构设计问题之选择和使用合适的UI库如何解决
Android项目架构设计问题之选择和使用合适的UI库如何解决
126 0
|
XML Android开发 UED
💥Android UI设计新风尚!掌握Material Design精髓,让你的界面颜值爆表!🎨
【7月更文挑战第28天】随着移动应用市场的发展,用户对界面设计的要求不断提高。Material Design是由Google推出的设计语言,强调真实感、统一性和创新性,通过模拟纸张和墨水的物理属性创造沉浸式体验。它注重色彩、排版、图标和布局的一致性,确保跨设备的统一视觉风格。Android Studio提供了丰富的Material Design组件库,如按钮、卡片等,易于使用且美观。
499 1

热门文章

最新文章