关闭

Android--Butter Knife

标签: github
581人阅读 评论(1) 收藏 举报
分类:

github:https://github.com/JakeWharton/butterknife;
使用指南:http://jakewharton.github.io/butterknife/

ButterKnife 优势:
1.强大的View绑定和Click事件处理功能
2.方便的处理Adapter里的ViewHolder绑定问题

使用心得:
1.Activity 中ButterKnife.bind(this);必须在setContentView();之后,且父类bind绑定后,子类不需要再bind;
2.Fragment ButterKnife.bind(this, rootView);
3.属性不能用private or static 修饰,否则会报错

一:配置:
app–build.gradle

apply plugin: 'com.neenbedankt.android-apt'
dependencies {
compile 'com.jakewharton:butterknife:8.0.1'
apt 'com.jakewharton:butterknife-compiler:8.0.1'
}

gradle–build.gradle

dependencies {
    classpath 'com.android.tools.build:gradle:2.1.0'
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
}

二:使用:

text = (TextView) findViewById(R.id.text);
text.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

    }
});

可以写成:

@BindView(R.id.text)
TextView text;
@OnClick({R.id.text})
void Click() {
    Toast.makeText(this, "text", Toast.LENGTH_LONG).show();
}
public class MainActivity extends AppCompatActivity {
@BindView(R.id.text)
    TextView text;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
text = (TextView) findViewById(R.id.text);
text.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

            }
        });
}


@OnClick({R.id.text})
void Click() {
        Toast.makeText(this, "text", Toast.LENGTH_LONG).show();
}
}

目前是简单体验一下,接下来,我们讲解更多的使用方法:
1–Base:
ButterKnife.bind(this)需要与Activity绑定到一起,而绑定Activity 必须在setContentView之后:

public abstract class BaseActivity extends AppCompatActivity {
public abstract int getContentViewId();
    private Unbinder unbinder;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getContentViewId());
unbinder = ButterKnife.bind(this);
initViews(savedInstanceState);
}

protected abstract void initViews(Bundle bundle);

/**
     * 解除绑定
     */
@Override
protected void onDestroy() {
super.onDestroy();
unbinder.unbind();
}
}
public abstract class BaseFragment extends Fragment {
public abstract int getContentViewId();
    protected Context context;
    protected View rootView;
    private Unbinder unbinder;

@Nullable
    @Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(getContentViewId(), container, false);
unbinder = ButterKnife.bind(this, rootView);
        this.context = getActivity();
initViews(savedInstanceState);
        return rootView;
}

protected abstract void initViews(Bundle bundle);

@Override
public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();
}
}

2–View:

@BindView(R.id.text)
TextView text;

@BindView(R.id.button)
Button button;

3–资源

@BindString(R.string.app_name)  
String appName;//sting  
@BindColor(R.color.red)  
int textColor;//颜色  
@BindDrawable(R.mipmap.ic_launcher)  
Drawable drawable;//drawble  
@Bind(R.id.imageview)  
ImageView mImageView;  
@Bind(R.id.checkbox)  
CheckBox mCheckBox;  
@BindDrawable(R.drawable.selector_image)  
Drawable selector;  

4–ViewHolder:
—-减少更多重复代码:

public class MyAdapter extends BaseAdapter {
  @Override 
  public View getView(int position, View view, ViewGroup parent) {
    ViewHolder holder;
    if (view != null) {
      holder = (ViewHolder) view.getTag();
    } else {
      view = inflater.inflate(R.layout.whatever, parent, false);
      //此处为节省代码
      holder = new ViewHolder(view);
      view.setTag(holder);
    }
    holder.name.setText("John Doe");

    return view;
  }


staticclassViewHolder{
@BindView(R.id.title) 
TextView name;
@BindView(R.id.job_title)
TextView jobTitle;
publicViewHolder(View view){
         ButterKnife.bind(this, view);
}
}

5–绑定View集合:

@BindViews ({R.id.button,R.id.button2,R.id.button3})
List<Button> button;

6–批量处理事件:
—-批量处理View事件

ButterKnife.apply(button);
ButterKnife.apply(button, ENABLED,false);
ButterKnife.apply(button, View.ALPHA, 0.0f);

—设置统一处理:

static final ButterKnife.Action<View> DISABLE = new ButterKnife.Action<View>() {
@Override
public void apply(View view, int index) {
        view.setEnabled(false);
}
};
static final ButterKnife.Setter<View, Boolean> ENABLED = new ButterKnife.Setter<View, Boolean>() {
@Override
public void set(View view, Boolean value, int index) {
        view.setEnabled(value);
}
};

7–View事件的监听:
–1:监听器参数可选

@OnClick({R.id.button})
void Click() {
    Toast.makeText(this, "text", Toast.LENGTH_LONG).show();
}
--2:
@OnClick({R.id.button})
void Click(View view) {
switch (view.getId()) {
case R.id.button:
            Toast.makeText(this, "text", Toast.LENGTH_LONG).show();
            break;
}

}

–3:定义一个类型,自动转换:

@OnClick({R.id.button})
void Click(Button btn) {
    btn.setText("onClick");
Toast.makeText(this, "text", Toast.LENGTH_LONG).show();
}

–4:继承View,也可使用监听:
—-自定义View,可以不指定ID,绑定自己的监听

public class CommitButton extends Button {
    public CommitButton(Context context) {
        super(context);
    }

    public CommitButton(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CommitButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


    @OnClick
    void click(){

    }
}

三:空处理:
—-默认情况下,“绑定”和“监听”绑定都是必需的。如果不能找到目标视图,则将抛出异常。

@Nullable
@BindView(R.id.button)
Button button;
而针对事件监听处理:
@Optional
@OnClick(R.id.button)
void Click() {
    Toast.makeText(this, "text", Toast.LENGTH_LONG).show();
}

四:添加多回调方法的监听的使用方法,利用指定回调,实现想回调的方法
–1:listView:

@OnItemClick(value=R.id.listView)
void onItemSelected() {

}

@OnItemLongClick()
void onItemLongClick(ListView listView){

}

–2:EditText

@BindView(R.id.edit)
EditText edit;
@OnTextChanged(value = R.id.edit, callback = OnTextChanged.Callback.BEFORE_TEXT_CHANGED)
void beforeTextChanged(CharSequence s, int start, int count, int after) {

}
@OnTextChanged(value = R.id.edit, callback = OnTextChanged.Callback.TEXT_CHANGED)
void onTextChanged(CharSequence s, int start, int before, int count) {

}
@OnTextChanged(value = R.id.edit, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
void afterTextChanged(Editable s) {

}

以下是源码:可以看出,我们在正常使用某个方法的时候,系统都会提供和原生一样的参数供我们使用,所以,可以了解到我们在使用方法时,参数可以保持和原生方法参数一致并使用(其他控件方法也适用):

@Target(METHOD)
@Retention(CLASS)
@ListenerClass(
    targetType = "android.widget.TextView",
    setter = "addTextChangedListener",
    type = "android.text.TextWatcher",
    callbacks = OnTextChanged.Callback.class
)
public @interface OnTextChanged {
  @IdRes int[] value() default { View.NO_ID };

  Callback callback() default Callback.TEXT_CHANGED;

  enum Callback {
    @ListenerMethod(
        name = "onTextChanged",
        parameters = {
            "java.lang.CharSequence",
            "int",
            "int",
            "int"
        }
    )
    TEXT_CHANGED,
    @ListenerMethod(
        name = "beforeTextChanged",
        parameters = {
            "java.lang.CharSequence",
            "int",
            "int",
            "int"
        }
    )
    BEFORE_TEXT_CHANGED,
    @ListenerMethod(
        name = "afterTextChanged",
        parameters = "android.text.Editable"
    )
    AFTER_TEXT_CHANGED,
  }
}

五:在使用整体View,或者Dialog使用:符合使用场景:

View view = LayoutInflater.from(context).inflate(R.layout.thing, null);
TextView firstName = ButterKnife.findById(view, R.id.first_name);
TextView lastName = ButterKnife.findById(view, R.id.last_name);
ImageView photo = ButterKnife.findById(view, R.id.photo);

完结:

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:32521次
    • 积分:795
    • 等级:
    • 排名:千里之外
    • 原创:51篇
    • 转载:0篇
    • 译文:0篇
    • 评论:4条
    最新评论