繼第22篇已經可以綁定fragment跟viewpager那我們就在fragment中加入一些東西吧,今天來試著生成QRcode
首先是xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/qrbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="56dp"
android:text=" 生成QRcode "
android:background="@drawable/nsq"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="@+id/camerabutton"
app:layout_constraintVertical_bias="0.0" />
<Button
android:id="@+id/camerabutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="88dp"
android:text="開啟相機"
android:background="@drawable/nsq"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.62"
app:layout_constraintStart_toEndOf="@+id/qrbutton" />
<EditText
android:id="@+id/edittext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="160dp"
android:ems="10"
android:inputType="textPersonName"
android:hint="請輸入網址或文字"
android:gravity="center"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="@+id/camerabutton"
app:layout_constraintHorizontal_bias="0.492"
app:layout_constraintStart_toStartOf="@+id/qrbutton" />
<ImageView
android:id="@+id/qrcode"
android:layout_width="275dp"
android:layout_height="275dp"
app:layout_constraintBottom_toTopOf="@+id/edittext"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.722"/>
</androidx.constraintlayout.widget.ConstraintLayout>
再來是
public class ScanActivity extends BaseActivity implements View.OnClickListener{
Button qrbutton;
Button camerabutton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan);
qrbutton=findViewById(R.id.qrbutton);
qrbutton.setOnClickListener(this);
camerabutton=findViewById(R.id.camerabutton);
camerabutton.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.qrbutton:
getCode();
break;
case R.id.camerabutton:
start(CameraActivity.class);
break;
}
}
public void getCode(){
ImageView ivCode=findViewById(R.id.qrcode);
EditText etContent=findViewById(R.id.edittext);
BarcodeEncoder encoder = new BarcodeEncoder();
try{
Bitmap bit = encoder.encodeBitmap(etContent.getText().toString()
,BarcodeFormat.QR_CODE,250,250);
ivCode.setImageBitmap(bit);
}catch (WriterException e){
e.printStackTrace();
}
}
}
成果如下