ViewBinding 视图绑定

1. 介绍

  1.1 官方概述地址视图绑定icon-default.png?t=M85Bhttps://developer.android.google.cn/topic/libraries/view-binding

  1.2 build.gradle 文件中引用

  viewBinding {
        enabled true
    }
  //高版本引用
  buildFeatures {
        viewBinding = true
    }

2. Java 开发中使用

  2.1 Fragment 布局文件 fragment_blank.xml




    

  2.2 BlankFragment.java 中调用

public class BlankFragment extends Fragment {
    private FragmentBlankBinding binding;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = FragmentBlankBinding.inflate(getLayoutInflater());
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        binding.textView.setTextSize(30f);
        binding.textView.setText("I am from fragment layout.");
    }
}

  2.3 activity 布局文件 activity_main.xml




    

    

    

    

    

  2.4 MainActivity.java 文件调用

public class MainActivity extends AppCompatActivity {
    ActivityMainBinding binding;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        binding.textView1.setText("View");
        binding.textView2.setText("binding");
    }
}

3. Kotlin 中调用

  3.1 布局文件与 java 一致

  3.2 BlankFragmnet.kt 文件中调用

class BlankFragment : Fragment() {
    private lateinit var binding: FragmentBlankBinding
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentBlankBinding.inflate(layoutInflater)
        return binding.root
    }
    
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.textView.textSize = 20.0f
        binding.textView.text = "BlankFragment"
    }
}

  3.3 MainActivity.kt 中调用

class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        binding.textView1.text = "View"
        binding.textView2.text = "Binding"
    }
}

你可能感兴趣的:(Jetpack,Kotlin,Android,Kotlin,Jetpack)