ButterKnife项目级应用

具体的倒入步骤请参考小编的另一片文章《ButterKnife使用详解》,本文只讲述如何在项目中应用

1.每个项目都会有一个BaseActivity,就在这个父类上做文章。
代码如下:

package song.peter.com.butterknifedemo;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;

import butterknife.ButterKnife;

public abstract class BaseActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
        ButterKnife.bind(this);
    }

    public abstract int getLayoutId();

}

2.MainActivity继承父类,并实现父类的抽象方法,代码如下:

package song.peter.com.butterknifedemo;

import android.os.Bundle;
import android.view.View;
import android.widget.CheckedTextView;
import android.widget.QuickContactBadge;
import android.widget.Toast;
import android.widget.ToggleButton;

import butterknife.BindView;
import butterknife.OnClick;

public class MainActivity extends BaseActivity {


    @BindView(R.id.checkedTextView)
    CheckedTextView checkedTextView;
    @BindView(R.id.toggleButton)
    ToggleButton toggleButton;
    @BindView(R.id.quickContactBadge)
    QuickContactBadge quickContactBadge;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    @OnClick({R.id.checkedTextView, R.id.toggleButton, R.id.quickContactBadge})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.checkedTextView:
                Toast.makeText(getApplicationContext(),"厉害了checkedTextView",Toast.LENGTH_LONG).show();
                break;
            case R.id.toggleButton:
                Toast.makeText(getApplicationContext(),"厉害了toggleButton",Toast.LENGTH_LONG).show();
                break;
            case R.id.quickContactBadge:
                Toast.makeText(getApplicationContext(),"厉害了quickContactBadge",Toast.LENGTH_LONG).show();
                break;
        }
    }
}

上述代码页用到了ButterKnife的控件绑定和事件绑定(多个控件的绑定),OK,搞定。

你可能感兴趣的:(ButterKnife项目级应用)