kotlin中ViewBinding的使用
ViewBinding的优点:
仅仅支持绑定 View
不需要在布局文件中添加layout标签
需要在模块级build.gradle文件中添加 viewBinding = true 即可使用
效率高于DataBinding,因为避免了与数据绑定相关的开销和性能问题
相比于kotlin-android-extensions插件避免了空异常
Gradle配置:
// Android Studio 3.6 android { viewBinding { enabled = true } } // Android Studio 4.0 android { buildFeatures { viewBinding = true } }
ViewBinding简单使用:
import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Toast import com.example.mychartdemo.databinding.ActivityMain2Binding class MainActivity2 : AppCompatActivity() { private lateinit var binding: ActivityMain2Binding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMain2Binding.inflate(layoutInflater) setContentView(binding.root) binding.btn.setOnClickListener { Toast.makeText(this,"点击了按钮",Toast.LENGTH_SHORT).show() } } }
Fragment
class HomeFragment: BaseFragment() { private lateinit var binding: FragmentHomeBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentHomeBinding.inflate(inflater,container,false) return binding.root } }
java中使用
1、Activity中
public class MainActivity extends AppCompatActivity { private ActivityMainBinding binding; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = ActivityMainBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); binding.tvText.setText("呵呵fff哈哈哈"); } }
2、Fragment中
public class HomeFragment extends Fragment { private FragmentHomeBinding binding; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { binding = FragmentHomeBinding.inflate(inflater,container,false); binding.tvText.setText("呵呵哈哈哈"); return binding.getRoot(); } }
参考于:
https://blog.csdn.net/tanlove1314/article/details/114240299
https://www.jianshu.com/p/66728b95baaa
https://www.cnblogs.com/ymtianyu/p/13208548.html