在Xamarin.Forms中输入自定义渲染器(为Android添加所有边框)

时间:2017-03-22 09:23:50

标签: android android-edittext xamarin.forms custom-renderer

我有一个问题。我需要使用Xamarin.Forms将所有边框添加到Android中的条目。我在PCL中创建了渲染器类,并在xaml文件中引用它。然后我在Android Project中为渲染器创建了特定的类。 我有这个:

[assembly: ExportRenderer (typeof(EntryCustom), ypeof(EntryRendererCustom))]
namespace InstagramApp.Droid.Renderers
{
 public class EntryRendererCustom : EntryRenderer
 {
    protected override void OnElementChanged(ElementChangedEventArgs<Entry>, e)
    {
        base.OnElementChanged(e);

        if(Control != null)
        {

        }
    }

  }
}

现在我必须在IF语句中添加代码,但我是xamarin和渲染器的新手。有人能帮我吗?如果有人也可以向我解释一些关于如何接近自定义渲染器的基础知识,那对我来说可能就是黄金。谢谢大家!

3 个答案:

答案 0 :(得分:4)

这是你可以做到的:

[assembly: ExportRenderer(typeof(Entry), typeof(EntryRendererImplementation))]
namespace MyProject.Droid.Renderers
{
    public class EntryRendererImplementation : EntryRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
        {
            base.OnElementChanged(e);
            if (Control != null)
            {
                Control.Background = this.Resources.GetDrawable(Resource.Drawable.RoundedCornerEntry);
                Control.SetPadding(10,10,10,3);
            }
        }
    }
}

您必须在Android项目的 Resources / drawable / RoundedCornerEntry.xml 中创建此文件

<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_focused="true" >
    <shape android:shape="rectangle">
      <gradient
          android:startColor="@color/entry_background"
          android:endColor="@color/entry_background"
          android:angle="270" />
      <stroke
          android:width="1dp"
          android:color="@color/entry_border" />
      <corners
          android:radius="6dp" />
    </shape>
  </item>
  <item>
    <shape android:shape="rectangle">
      <gradient
          android:startColor="@color/entry_background"
          android:endColor="@color/entry_background"
          android:angle="270" />
      <stroke
          android:width="1dp"
          android:color="#c6c6c6" />
      <corners
          android:radius="6dp" />
    </shape>
  </item>
</selector>

当然,您需要更新 Resources / values / colors.xml 文件 类似的东西:

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <color name="entry_background">#ffffff</color>
  <color name="entry_border">#BDBDBD</color>
</resources>

你去吧!

答案 1 :(得分:0)

答案 2 :(得分:0)

很好理解如何使用Custome Renderers有很多关于它的书面和视频教程,所以如果你自己检查一下会更好,

还有其他方法可以添加边框而无需使用自定义渲染器,这取决于您在说边框时想到的图像

  1. 将条目放在框架内
  2. 将条目放在boxView上方,这样您可以更好地控制“边框”,例如厚度,不透明度甚至动画(也许您希望边框闪烁)
  3. 要做第二种方法,我会像这样使用网格

    <Grid>
       <BoxView Color="Blue" />
       <Entry/>
    </Grid>
    

    此处的顺序在网格中很重要,对于这种情况,首先定义的元素放在下面。另一个显而易见的观点是BoxView的高度和宽度应该略大于Enrty的高度和宽度,框越大边框越厚(我现在还在谈论代码;)