【发布时间】:2020-10-13 05:23:21
【问题描述】:
我正在开发使用 Zxing 扫描片段上的二维码的 Android 应用程序,为了实现这一点,我按照本教程获得了所需的结果。Link I Followed to Scan QR on Fragment
我用来在**QRCodeFragment ** Fragment 上扫描二维码的代码看起来
class QRCodeFragment : Fragment() {
internal var txtName: TextView? = null
internal var txtSiteName: TextView? = null
internal var btnScan: Button? = null
internal var qrScanIntegrator: IntentIntegrator? = null
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater?.inflate(R.layout.fragment_qr_code, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
txtName = view.findViewById(R.id.name)
txtSiteName = view.findViewById(R.id.site_name)
btnScan = view.findViewById(R.id.btnScan)
btnScan!!.setOnClickListener { performAction() }
qrScanIntegrator = IntentIntegrator.forFragment(this)
qrScanIntegrator?.setOrientationLocked(false)
// Different Customization option...
qrScanIntegrator?.setPrompt(getString(R.string.scan_a_code))
qrScanIntegrator?.setCameraId(0) // Use a specific camera of the device
qrScanIntegrator?.setBeepEnabled(false)
qrScanIntegrator?.setBarcodeImageEnabled(true)
super.onViewCreated(view, savedInstanceState)
}
private fun performAction() {
qrScanIntegrator?.initiateScan()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
val result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data)
if (result != null) {
// If QRCode has no data.
if (result.contents == null) {
Toast.makeText(activity, R.string.result_not_found, Toast.LENGTH_LONG).show()
} else {
// If QRCode contains data.
try {
// Converting the data to json format
val obj = JSONObject(result.contents)
// Show values in UI.
txtName?.text = obj.getString("name")
txtSiteName?.text = obj.getString("site_name")
} catch (e: JSONException) {
e.printStackTrace()
// Data not in the expected format. So, whole object as toast message.
Toast.makeText(activity, result.contents, Toast.LENGTH_LONG).show()
}
}
} else {
super.onActivityResult(requestCode, resultCode, data)
}
}
}
从我调用片段的主要活动就像
private fun ShowQRCodeFragment() {
val newFragment = QRCodeFragment()
val transaction1: FragmentTransaction = supportFragmentManager.beginTransaction();
transaction1.replace(R.id.frameLayout, newFragment);
transaction1.addToBackStack(null);
transaction1.commit();
}
在主片段中它显示类型不匹配,我指出它转到正在扩展的片段名称 Fragment()
public Fragment() {
initLifecycle();
}
【问题讨论】:
-
尝试找出提供和请求类的全名(包括包)。一个可能来自 AndroidX 或支持库,另一个来自主 API。
标签: android kotlin android-fragments fragment android-fragmentactivity