您的位置:首页 > 其它

利用开源框架ZXing增加二维码功能(by 星空武哥)

2016-04-27 12:29 363 查看
很多时候我们的项目中或用到二维的扫描功能,今天我就交给大家怎么利用开源ZXing,来扫描二维码?

这是个ZXing是精简版的,全版太大了,里面保留的扫描二维码和创建二维码。

http://download.csdn.net/detail/lsyz0021/9504050

首先新建一个Android项目:

Rq_scan:

布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
tools:context="com.bandeng2.lilu.rq_scan.MainActivity">
<Button
android:onClick="scan"
android:text="扫描二维码"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_gravity="center_horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:layout_margin="@dimen/activity_horizontal_margin"
android:text="扫描结果" />
<TextView
android:id="@+id/tv_result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:layout_margin="@dimen/activity_horizontal_margin"
/>
</LinearLayout>
布局的效果:



导入:zxing的lib包:然后是项目关联libzxing包



代码实现:

public class MainActivity extends AppCompatActivity {

private TextView tv_rsult;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv_rsult = (TextView) findViewById(R.id.tv_result);
}

public void scan(View view){
// 开启ZXing库中可以扫描的二维码的Activity
Intent intent = new Intent(this, CaptureActivity.class);
// 要有返回结果
startActivityForResult(intent,1);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if (resultCode == Activity.RESULT_OK){
// 获取返回结果
String result = data.getStringExtra("result");
// 将结果设置给TextView
tv_rsult.setText(result);
}
}
}


其实我们只是开启了CaptureActivity,然后回去返回结果,特别的简单

测试:这是从网上生成“学习二维码扫描和简单”所对应的二维码。



真机测试:



我们再增加生产二维码的功能

/**生产二维码*/
public void create(View view){
String result = et_text.getText().toString();
if (!TextUtils.isEmpty(result)){
Bitmap bitmap = EncodingUtils.createQRCode(result,500,500,
BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher));
image.setImageBitmap(bitmap);
}else{
Toast.makeText(this,"输入不能为空",Toast.LENGTH_LONG).show();

}

}


结果如下:



这样我们就简单的实现了二维码的扫描和生成了。

源码下载:https://github.com/lsyz0021/RSScan1.git
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: