package com.jopek.lectordecodi.ui.reader; import static com.jopek.lectordecodi.SharedPreferencesManager.getColor; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import androidx.activity.result.ActivityResultLauncher; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProvider; import com.jopek.lectordecodi.R; import com.jopek.lectordecodi.databinding.FragmentReaderBinding; import com.journeyapps.barcodescanner.ScanContract; import com.journeyapps.barcodescanner.ScanOptions; public class ReaderFragment extends Fragment { private final String TAG = "maks"; private FragmentReaderBinding binding; private TextView tvRead; private Button bStartRead; private Button bCopyCode; private String readCode = ""; // Register the launcher and result handler private final ActivityResultLauncher barcodeLauncher = registerForActivityResult(new ScanContract(), result -> { if (result.getContents() == null) { tvRead.setText("Reading code failed"); } else { readCode = result.getContents(); tvRead.setText("Readed: " + readCode); } }); public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ReaderViewModel readerViewModel = new ViewModelProvider(this).get(ReaderViewModel.class); binding = FragmentReaderBinding.inflate(inflater, container, false); View root = binding.getRoot(); tvRead = root.findViewById(R.id.read_from_code); bStartRead = root.findViewById(R.id.start_read); bCopyCode = root.findViewById(R.id.copy_read_from_code); binding.startRead.setBackgroundColor(getResources().getColor(getColor(getActivity()))); binding.copyReadFromCode.setBackgroundColor(getResources().getColor(getColor(getActivity()))); bStartRead.setOnClickListener(view -> { ScanOptions options = new ScanOptions(); options.setDesiredBarcodeFormats(ScanOptions.ALL_CODE_TYPES); options.setPrompt("Scan a QbaRCode"); options.setCameraId(0); // Use a specific camera of the device options.setBeepEnabled(false); options.setBarcodeImageEnabled(true); options.setOrientationLocked(false); barcodeLauncher.launch(options); }); bCopyCode.setOnClickListener(view -> { ClipboardManager clipboard = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE); ClipData clip = ClipData.newPlainText("label", readCode); clipboard.setPrimaryClip(clip); }); return root; } @Override public void onDestroyView() { super.onDestroyView(); binding = null; } }