This is my Activity function that the startActivity(i) unable go to the Fragment page after scanning a barcode, I have try that it can go to activity page and show the code successful but I need it go to Fragment page.
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()
}
}
})
This is my Fragment page. do I write anything wrong?
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
}
}
CodePudding user response:
You use intent to navigate to Activity
not to Fragment
.
You can:
Use fragment transactions to navigate to new
Fragment
in your currentActivity
Use intent to navigate to new
Activity
and in your newActivity
use fragment transactions to yourFragment
CodePudding user response:
You need to create a class that extends FragmentActivity and start your fragment there:
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();}
}
}
then fragment constructor:
public MyFragment() {
}
then from your calling activity, start your fragment activity in the normal way
Intent i = new Intent(YourActivity.this, MyFragment.class);
startActivity(i);