[gradle/kotlin] view binding 뷰 바인딩 설정 및 코드샘플

천현철·2021년 12월 14일
0

Android

목록 보기
35/43

Gradle Plugin 3.6.0:

android {
	viewBinding { 
    	enabled = true 
    } 
}

Android Studio 4.0 이상:

android { 
	buildFeatures { 
	viewBinding = true 
    } 
}

Activity:

class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding //activity_main.xml
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)        
    }
}

Fragment:

class ApisFragment : Fragment() {
    private var _binding: FragmentApiBinding? = null //fragment_api.xml
    private val binding get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentApiBinding.inflate(inflater, container, false)
        return binding.root        
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)                

        binding.clearLogBtn.setOnClickListener {
            binding.log.text = ""
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }    
}
profile
기도하지말고 행동하라

0개의 댓글