如何使用Intent从活动转到Fragment页面



这是我的活动函数,startActivity(i(在扫描条形码后无法转到片段页面,我尝试过它可以转到活动页面并成功显示代码,但我需要它转到片段页面。

barcodeDetector.setProcessor(object : Detector.Processor<Barcode> {
override fun release() {
Toast.makeText(applicationContext, "Scanner has been closed", Toast.LENGTH_SHORT)
.show()
}
override fun receiveDetections(detections: Detector.Detections<Barcode>) {
val barcodes = detections.detectedItems
if (barcodes.size() == 1) {
scannedValue = barcodes.valueAt(0).rawValue
runOnUiThread {
cameraSource.stop()
Toast.makeText(this@InsertStockInActivity, scannedValue, Toast.LENGTH_SHORT).show()
val i = Intent(this@InsertStockInActivity, comFragment::class.java)
.putExtra("cameraSource", scannedValue)
startActivity(i)
finish()
}
}else
{
Toast.makeText(this@InsertStockInActivity, "value- else", Toast.LENGTH_SHORT).show()
}
}
})

这是我的碎片页面。我写错什么了吗?

class comFragment : Fragment() {
private lateinit var binding: FragmentComBinding
private val nav by lazy { findNavController() }
private val vm: StockInViewModel by activityViewModels()
private val formatter = SimpleDateFormat("dd MMMM yyyy '-' hh:mm:ss a", Locale.getDefault())
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = FragmentComBinding.inflate(inflater, container, false)
//binding.btnScanBarcode.setOnClickListener{ nav.navigate(R.id.insertStockInActivity) }
val value = requireActivity().intent.getStringExtra("cameraSource")
binding.edtId.findViewById<EditText>(R.id.value)
return binding.root
}

}

您使用intent导航到Activity而不是Fragment

您可以:

  1. 使用碎片事务导航到当前Activity中的新Fragment

  2. 使用intent导航到新的Activity,并在新Activity中使用片段事务到Fragment

您需要创建一个扩展FragmentActivity的类,并在那里启动您的片段:

public class MyFragmentActivity extends YourActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null){
getSupportFragmentManager().beginTransaction()
.add(android.R.id.content, new MyFragment ()).commit();}
}
}

然后片段构造函数:

public MyFragment() {
}

然后从你的呼叫活动开始,以正常的方式开始你的碎片活动

Intent i = new Intent(YourActivity.this, MyFragment.class);
startActivity(i);

最新更新