码迷,mamicode.com
首页 > 其他好文 > 详细

ButterKnifer使用

时间:2019-11-26 13:22:24      阅读:60      评论:0      收藏:0      [点我收藏+]

标签:dbi   git   方法   parent   text   short   options   contain   depend   

ButterKnifer使用

1.集成

github地址: https://github.com/JakeWharton/butterknife

1.1在主Moduel中的使用

在主moduel中的build.gradle中添加一下配置

android {
  ...
  // Butterknife requires Java 8.
  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }
}

dependencies {
  implementation 'com.jakewharton:butterknife:10.2.0'
  annotationProcessor 'com.jakewharton:butterknife-compiler:10.2.0'
}

如果您使用的是Kotlin,请替换annotationProcessorkapt

1.2在Library projects项目中使用

1.在Android project的build.gradle中添加

buildscript {
  repositories {
    mavenCentral()
    google()
   }
  dependencies {
    classpath 'com.jakewharton:butterknife-gradle-plugin:10.2.0'
  }
}

2.在Library的buid.gradle中添加如下配置

apply plugin: 'com.android.library'
apply plugin: 'com.jakewharton.butterknife'

3.确保在Butter knife annotations中使用R2替换R。

class ExampleActivity extends Activity {
  @BindView(R2.id.user) EditText username;
  @BindView(R2.id.pass) EditText password;
...
}

2. ButterKnife的基本使用场景

2.1 在Activity中绑定ButterKnife:

    @BindView(R.id.bt)
    Button bt;
    @BindView(R.id.bt2)
    Button bt2;

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

    @OnClick({R.id.bt, R.id.bt2})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bt:
                Toast.makeText(this,"button1被点击了",Toast.LENGTH_LONG).show();
                break;
            case R.id.bt2:
                Toast.makeText(this,"button2被点击了",Toast.LENGTH_LONG).show();
                break;
        }
    }

2.2 在Fragment中绑定ButterKnife

    private Unbinder unbinder;
    @BindView(R.id.bt1)
    Button bt1;
    @BindView(R.id.bt2)
    Button bt2;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_first, container, false);
        unbinder= ButterKnife.bind(this,view);
        return view;
    }

    @OnClick({R.id.bt1, R.id.bt2})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bt1:
                break;
            case R.id.bt2:
                break;
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();//视图销毁时必须解绑
    }

2.3 在Adapter的ViewHolder中绑定ButterKnife

public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ViewHolder> {

    @BindView(R.id.img)
    ImageView img;
    @BindView(R.id.tv)
    TextView tv;
    private Context context;
    private List<Item> datas;

    public ItemAdapter(Context context, List<Item> datas) {
        this.context = context;
        this.datas = datas;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_rv, parent,
                false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.img.setImageResource(datas.get(position).getImgId());
        holder.tv.setText(datas.get(position).getContent());
        holder.img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
       
                Toast.makeText(context,"图片被点击了...",Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public int getItemCount() {
        return datas.size();
    }
    
    class ViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.img)
        ImageView img;
        @BindView(R.id.tv)
        TextView tv;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }
}

3. Butterknife具体使用

3.1 绑定View

1.单个控件id注解: @BindView()

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

2.布局内多个控件id注解; @BindViews()

@BindViews({R.id.butter,R.id.butter1,R.id.butter2})
    List<Button> buttons;

3.2 绑定资源文件

1.绑定string 字符串:@BindString()

@BindString(R.string.app_name) //绑定资源文件中string字符串
String name;

2.绑定array数组:@BindArray()

<resources>
<string name="app_name">开眼视频</string>

<string-array name="weather">
<item>高温</item>
<item>低温</item>
<item>阴天</item>
<item>雨天</item>
<item>晴天</item>
</string-array>

</resources>
@BindArray(R.array.weather) //绑定string资源里面array数组
String [] weathers ;

3.绑定颜色值:@BindColor( )

@BindColor( R.color.colorPrimary) //绑定color文件中颜色值
int colorPrimary; 

4.绑定Bitmap:@BindBitmap( )

@BindBitmap(R.mipmap.ic_launcher)
    Bitmap bitmap;

5.其他资源绑定:

@BindBool(R.bool.is_tablet) boolean isTablet; //绑定真假boolean

@BindFont(R.font.comic_sans) Typeface comicSans; //绑定字体文字

@BindDimen(R.dimen.horizontal_gap) int gapPx //绑定尺寸
@BindDimen(R.dimen.horizontal_gap) float gap; //绑定尺寸

@BindAnim(R.anim.fade_in) Animation fadeIn; //绑定动画

@BindDrawable(R.drawable.placeholder) Drawable placeholder;//绑定Drawable

3.3 绑定监听事件

1.绑定控件点击事件:@OnClick( )

  • 单个控件点击事件:
 @OnClick(R.id.butter)
    public void onClick(){
        Toast.makeText(this, "绑定单个view事件", Toast.LENGTH_SHORT).show();
    }
  • 多个控件同一点击事件:
@OnClick({R.id.share_wechat,R.id.share_moments,R.id.share_weibo})
 public void onClick(){
        Toast.makeText(this, "都执行此事件", Toast.LENGTH_SHORT).show();
    }
  • 多个控件点击事件:
  @OnClick({R.id.share_wechat,R.id.share_moments,R.id.share_weibo})
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.share_wechat:
                sharePlatform(Wechat.NAME);
                break;
            case R.id.share_moments:
                sharePlatform(WechatMoments.NAME);
                break;
            case R.id.share_weibo:
                sharePlatform(SinaWeibo.NAME);
                break;
        }
    }

2.绑定控件长按事件:@OnLongClick( )

@OnLongClick( R.id.button1 ) //给 button1 设置一个长按事件
public boolean onLongClick (){
    Toast.makeText(this, "is a long click", Toast.LENGTH_SHORT).show();
    return true ;
}

3.其他事件绑定

//选中,选中取消
@OnCheckedChanged(R.id.example) 
public void onChecked(boolean checked) {
    Toast.makeText(this, checked ? "Checked!" : "Unchecked!", Toast.LENGTH_SHORT).show();
}

//软键盘的功能按键
@OnEditorAction(R.id.example)
public  boolean onEditorAction(KeyEvent key) {
    Toast.makeText(this, "Pressed: " + key, Toast.LENGTH_SHORT).show();
    return true;
  }

//焦点改变
@OnFocusChange(R.id.example) 
public void onFocusChanged(boolean focused) {
   Toast.makeText(this, focused ? "Gained focus" : "Lost focus", Toast.LENGTH_SHORT).show();
  }

//Item长按,返回true则可以拦截onItemClick
@OnItemLongClick(R.id.example_list) 
public boolean onItemLongClick(int position) {
    Toast.makeText(this, "Long clicked position " + position + "!", Toast.LENGTH_SHORT).show();
    return true;
  }

//Item点击事件
@OnItemClick(R.id.example_list) 
public void onItemClick(int position) {
   Toast.makeText(this, "Clicked position " + position + "!", Toast.LENGTH_SHORT).show();
 }

//Item被选择事件
@OnItemSelected(R.id.example_list) 
public void onItemSelected(int position) {
    Toast.makeText(this, "Selected position " + position + "!", Toast.LENGTH_SHORT).show();
  }

//EditText里面的文本变化事件
@OnTextChanged(R.id.example) 
public void onTextChanged(CharSequence text) {
    Toast.makeText(this, "Text changed: " + text, Toast.LENGTH_SHORT).show();
  }

//页面改变事件
@OnPageChange(R.id.example_pager) 
public void onPageSelected(int position) {
   Toast.makeText(this, "Selected " + position + "!", Toast.LENGTH_SHORT).show();
  }

//触摸事件
@OnTouch(R.id.example)
public  boolean onTouch() {
    Toast.makeText(this, "Touched!", Toast.LENGTH_SHORT).show();
    return false;
  }

3.4 Action接口与Setter接口

Action接口主要是为了对View或者Views进行管理初始化等操作,而Setter接口其实就是对view或者views的属性或者值进行操作.使用 ButterKnife.apply()方法启用接口.

ButterKnife.Action<View> action = new ButterKnife.Action<View>() {
      @Override
      public void apply(@NonNull View view, int index) {
          if (view instanceof Button ){
              Button button = (Button) view;
              button.setText("点击我");
          }
      }
  };

    ButterKnife.Setter<View,Boolean> setter = new ButterKnife.Setter<View, Boolean>() {
        @Override
        public void set(@NonNull View view, Boolean value, int index) {
            view.setEnabled(value);
        }
    };


@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        ButterKnife.apply(buttons,action);//初始化或修改每个view的属性值
        ButterKnife.apply(buttons,setter,true);
    }

4 ButterKnife Zelezny插件

打开Android studio:点击File--->Settings--->Plugins--->搜索 Butterknife Zelezny--->下载安装--->重启Android studio.

参考;

Android常用之Butterknife使用详解

ButterKnifer使用

标签:dbi   git   方法   parent   text   short   options   contain   depend   

原文地址:https://www.cnblogs.com/wangjiaghe/p/11934543.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!