如何在Xamarin中构造自定义视图 [英] How to construct custom views in xamarin
问题描述
有没有能让我在xamarin中设计自定义视图的教程?我想使用xamarin为我的android应用构建捏缩放功能.
Is there any tutorial which will enable me to design custom views in xamarin?I want to build pinch zoom functionality for my android app using xamarin.
我尝试了以下代码,但无法正常工作,总是出现android.view.InflateException: Binary XML file line #1: Error inflating class LA_Application.ZoomView
错误
I have tried following code,but its not working,I am always getting android.view.InflateException: Binary XML file line #1: Error inflating class LA_Application.ZoomView
error
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Util;
using Android.Views;
using Android.Widget;
using Android.Graphics;
namespace LA_Application
{
public class ZoomView : FrameLayout
{
private ScaleGestureDetector mScaleDetector;
private static float mScaleFactor = 1.0f;
public ZoomView (Context context) : base (context)
{
Initialize ();
}
public ZoomView (Context context, IAttributeSet attrs) : base (context,attrs)
{
Initialize ();
}
public ZoomView (Context context, IAttributeSet attrs, int defStyle) : base (context, attrs, defStyle)
{
Initialize ();
}
void Initialize ()
{
mScaleDetector = new ScaleGestureDetector(Context, new ScaleListener());
}
public override bool OnTouchEvent (MotionEvent e)
{
mScaleDetector.OnTouchEvent(e);
return true;
}
protected override void OnDraw(Android.Graphics.Canvas canvas)
{
base.OnDraw(canvas);
canvas.Save();
canvas.Scale(mScaleFactor, mScaleFactor);
canvas.Restore();
}
}
private class ScaleListener : ScaleGestureDetector.SimpleOnScaleGestureListener
{
public override bool OnScale(ScaleGestureDetector detector)
{
mScaleFactor *= detector.ScaleFactor;
// Don't let the object get too small or too large.
mScaleFactor = Math.Max(0.1f, Math.Min(mScaleFactor, 5.0f));
return true;
}
}
}
}
和布局文件中
<?xml version="1.0" encoding="utf-8"?>
<LA_Application.ZoomView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/my_view" />
活动代码
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
SetContentView(Resource.Layout.zoomview);
/*some code*/
}
推荐答案
我建议您查看此Java Android教程,以了解您需要设置的内容:
I would suggest checking out this Java Android tutorial to get an idea of what you need to setup:
http://developer.android.com/training/custom-views/index.html
您可能需要为自定义视图创建一个属性xml文件.
You may need to create an attributes xml file for your custom view.
您可能要考虑的另一种方法是使用片段而不是视图:
Another approach you may want to consider is to use a fragment instead of a view:
http://docs.xamarin.com/guides/android/platform_features/Fragments/fragments_walkthrough
这篇关于如何在Xamarin中构造自定义视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!