关于ButterKnife和@BindView的关系与@OnClick()方法的点击事件获取不到以及报空错误

使用@BindView注解绑定页面控件,省去了以前麻烦的findViewById()
使用范例:在添加了依赖以后的动作

 //获取控件
        @BindView(R.id.name)//1.使用 @BindView注解
        EditText name;

在onCreat(){}方法里~的 setContentView(R.layout.activity_main);
2.下面放上 ButterKnife.bind(this);
//绑定处理

  ButterKnife.bind(this);

3注意,一定是在 setContentView();的下面添加,否则会找不到视图
示例:

public class XinActivity extends AppCompatActivity {
    
        //获取控件
        @BindView(R.id.name)
        EditText name;
    
        @BindView(R.id.btn)
        Button btn;
        @BindView(R.id.txt)
        TextView txt;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_xin);
    
            //绑定处理
            ButterKnife.bind(this);
        }

如果控件要有点击事件之类的动作,要设置监听,不然就是实现了监听器的@OnClick方法也获取不到控件/示例:
第一种

 /**
     * 传的数据
     */
    @BindView(R.id.sc_vipId)
    TextView vipId;//会员id
    @BindView(R.id.tx_orgId)
    TextView orgId;//组织id
 @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        //获取页面
        setContentView(R.layout.activity_book_order_bill_save);
        //绑定@BindView
        ButterKnife.bind(this);
        
        vipId.setOnClickListener(this);
        orgId.setOnClickListener(this);
        }

第二种

/**
 * 9:00,11:00,15:00设置监听
 */
        Button bt9 = findViewById(R.id.time_nine_oclock);
        Button bt11 = findViewById(R.id.time_eleven_oclock);
        Button bt15 = findViewById(R.id.time_fifteen_oclock);
        bt9.setOnClickListener(this);
        bt11.setOnClickListener(this);
        bt15.setOnClickListener(this);
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值