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

回答編集履歴

1

追記

2021/04/20 09:40

投稿

hoshi-takanori
hoshi-takanori

スコア7903

answer CHANGED
@@ -1,4 +1,60 @@
1
1
  それは synthetic import という機能でしたが、残念ながら最近廃止になってしまいました。
2
2
  代わりに findViewById または [view binding](https://developer.android.com/topic/libraries/view-binding?hl=ja) をお使いください。
3
3
  参考: [Kotlin Android Extensions syntheticsのdeprecatedに伴う対応 - Qiita](https://qiita.com/taigen/items/116ff3856eab6634e47b)
4
- 参考: [https://teratail.com/questions/330555#reply-456902](https://teratail.com/questions/330555#reply-456902)
4
+ 参考: [https://teratail.com/questions/330555#reply-456902](https://teratail.com/questions/330555#reply-456902)
5
+
6
+ ---
7
+
8
+ ### findViewById の場合
9
+
10
+ ```diff
11
+ + val hitText = findViewById<TextView>(R.id.hitText)
12
+ hitText.text = getString(R.string.hit_text)
13
+
14
+ + val loseText = findViewById<TextView>(R.id.loseText)
15
+ loseText.text = getString(R.string.lose_text)
16
+ ```
17
+
18
+ ---
19
+
20
+ ### view binding の場合
21
+
22
+ app/build.gradle の android { 〜 } に viewBinding を追加
23
+
24
+ ```diff
25
+ android {
26
+ // 略
27
+
28
+ + viewBinding {
29
+ + enabled = true
30
+ + }
31
+ }
32
+ ```
33
+
34
+ MainActivity.kt を修正
35
+
36
+ ```diff
37
+ -import **kotlinx**.android.synthetic.main.activity_main.*
38
+ +import com.example.highandlow.databinding.ActivityMainBinding
39
+
40
+ class MainActivity : AppCompatActivity() {
41
+ + private lateinit var binding: ActivityMainBinding
42
+
43
+ // 略
44
+
45
+ override fun onCreate(savedInstanceState: Bundle?) {
46
+ super.onCreate(savedInstanceState)
47
+ - setContentView(R.layout.activity_main)
48
+ + binding = ActivityMainBinding.inflate(layoutInflater)
49
+ + setContentView(binding.root)
50
+ }
51
+
52
+ override fun onResume() {
53
+ // 略
54
+
55
+ - **hitText**.text = getString(R.string.hit_text)
56
+ - **loseText**.text = getString(R.string.lose_text)
57
+ + binding.hitText.text = getString(R.string.hit_text)
58
+ + binding.loseText.text = getString(R.string.lose_text)
59
+
60
+ ```