问题
In my Xamarin.Android app, I want to use ZXing to scan barcode. I want to display the scanner in the view of an activity.
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:weightSum="5">
<Button
android:text="Scan with Default Overlay"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/buttonScanDefaultView"
android:layout_weight="1" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/scanView"
android:layout_weight="2" />
</LinearLayout>
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
scannerFragment = new ZXingScannerFragment ();
scannerFragment.CustomOverlayView = CustomOverlayView;
scannerFragment.UseCustomOverlayView = UseCustomOverlayView;
scannerFragment.TopText = TopText;
scannerFragment.BottomText = BottomText;
this.FragmentManager.BeginTransaction ()
.Replace (Resource.Id.scanView, scannerFragment, "ZXINGFRAGMENT")
.Commit ();
}
I'm getting an error stating that I cannot convert support.v4.fragment into android.app.Fragment.
Can anyone advise what I'm doing wrong and how should I approach this to get the scanner view (of ZXing) in a layout of my current activity.
回答1:
ZXingScannerFragment
derives from Android.Support.V4.App.Fragment
while the Activity.FragmentManager
expects fragments derived from Android.App.Fragment
.
Now, how to fix that:
Inherit your activity from any activity that works with Android.Support.V4. Easiest would to use
Android.Support.V4.App.FragmentActivity
from packageXamarin.Android.Support.v4
that is already installed byZXing.Net.Mobile
package as a dependency.When you have correct activity, you can use
this.SupportFragmentManager
instead ofthis.FragmentManager
to work with Support.V4-based fragments.
So, layout you have is good. Code should be updated to something like:
using Android.App;
using Android.Widget;
using Android.OS;
using ZXing.Mobile;
using Android.Support.V4.App;
namespace ZXingSample
{
[Activity(Label = "ZXing Sample", MainLauncher = true, Icon = "@mipmap/icon")]
public class MainActivity : FragmentActivity
{
int count = 1;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Main);
var scannerFragment = new ZXingScannerFragment();
scannerFragment.UseCustomOverlayView = false;
scannerFragment.TopText = "Scan your code";
scannerFragment.BottomText = "Then proceed";
this.SupportFragmentManager.BeginTransaction()
.Replace(Resource.Id.scanView, scannerFragment, "ZXINGFRAGMENT")
.Commit();
}
}
}
Launching the app, you will see your scanner:
来源:https://stackoverflow.com/questions/43034381/how-to-make-zebra-xing-zxing-as-subview-in-xamarin-android