当前位置: 首页 > 工具软件 > ButterKnife > 使用案例 >

ButterKnife学习

阮轶
2023-12-01

ButterKnife是为了将代码变得更加简洁,提高可读性的一种标签注入的框架。

  1. 配置方法可参考如下链接:
    http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2015/0102/2247.html

  2. 使用方法如下:

情况1 @InjectView. 绑定xml中的view到一个自定义的View变量中

package com.example.butterknife;

import butterknife.ButterKnife;
import butterknife.InjectView;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {

    @InjectView(R.id.button1) 
    View button1;
    @InjectView(R.id.button2) 
    View button2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ButterKnife.inject(this);
//      Button button1,button2;
//      button1=(Button) this.findViewById(R.id.button1);

        button1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                System.out.println("button1 ****************");
                Toast.makeText(MainActivity.this, "button1 pressed!", 0).show();
            }
        });
        button2.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                System.out.println("button2 ****************");
                Toast.makeText(MainActivity.this, "button2 pressed!", Toast.LENGTH_SHORT).show();
            }
        });

    }

情况2 @OnClick:为组件添加响应事件


public class MainActivity extends ActionBarActivity {

    @OnClick(R.id.button1)
    public void onClick1(){
        Toast.makeText(MainActivity.this, "button1 pressed!", 0).show();
    }

    @OnClick(R.id.button2)
    public void onClick2(){
        Toast.makeText(MainActivity.this, "button1 pressed!", 0).show();
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ButterKnife.inject(this);
        }
 类似资料: