teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

1

他の解決方法を追記

2019/05/27 16:26

投稿

f-miyu
f-miyu

スコア1625

answer CHANGED
@@ -12,4 +12,96 @@
12
12
 
13
13
  s.Focus();
14
14
  }
15
+ ```
16
+
17
+ ---
18
+ ちょっと本格的に、画面が表示されるタイミングでフォーカスを当てる様なエフェクトを作ってみました。
19
+
20
+ Androidプロジェクト
21
+ ```C#
22
+ [assembly: ResolutionGroupName("BlankApp1")]
23
+ [assembly: ExportEffect(typeof(FocusEffect), nameof(FocusEffect))]
24
+ namespace BlankApp1.Droid
25
+ {
26
+ public class FocusEffect : PlatformEffect
27
+ {
28
+ private Listener _listener;
29
+
30
+ protected override void OnAttached()
31
+ {
32
+ _listener = new Listener(this);
33
+ Control.ViewTreeObserver.AddOnPreDrawListener(_listener);
34
+ }
35
+
36
+ protected override void OnDetached()
37
+ {
38
+ if (_listener != null)
39
+ {
40
+ Control.ViewTreeObserver.RemoveOnPreDrawListener(_listener);
41
+ _listener = null;
42
+ }
43
+ }
44
+
45
+ private void Focus()
46
+ {
47
+ (Element as VisualElement)?.Focus();
48
+
49
+ if (_listener != null)
50
+ {
51
+ Control.ViewTreeObserver.RemoveOnPreDrawListener(_listener);
52
+ _listener = null;
53
+ }
54
+ }
55
+
56
+ private class Listener : Java.Lang.Object, ViewTreeObserver.IOnPreDrawListener
57
+ {
58
+ private FocusEffect _effect;
59
+
60
+ public Listener(FocusEffect effect)
61
+ {
62
+ _effect = effect;
63
+ }
64
+
65
+ public bool OnPreDraw()
66
+ {
67
+ _effect.Focus();
68
+ return true;
69
+ }
70
+ }
71
+ }
72
+ }
73
+ ```
74
+
75
+ 共通プロジェクト
76
+ ```C#
77
+ namespace BlankApp1.Effects
78
+ {
79
+ public class FocusEffect : RoutingEffect
80
+ {
81
+ public FocusEffect() : base($"BlankApp1.{nameof(FocusEffect)}")
82
+ {
83
+ }
84
+ }
85
+ }
86
+ ```
87
+
88
+ ```xml
89
+ <?xml version="1.0" encoding="utf-8" ?>
90
+ <ContentPage
91
+ x:Class="BlankApp1.Views.LoginPage"
92
+ xmlns="http://xamarin.com/schemas/2014/forms"
93
+ xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
94
+ xmlns:b="clr-namespace:BlankApp1.Behavior"
95
+ xmlns:e="clr-namespace:BlankApp1.Effects"
96
+ xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
97
+ prism:ViewModelLocator.AutowireViewModel="True">
98
+
99
+ <StackLayout Style="{StaticResource StackLayoutStyle}">
100
+ <Entry x:Name="User" >
101
+ <Entry.Effects>
102
+ <e:FocusEffect />
103
+ </Entry.Effects>
104
+ </Entry>
105
+ </StackLayout>
106
+ </ContentPage>
15
107
  ```