Context context;
private Button rightButton;
private Button leftButton;
private TextView titletext;
private OnLeftAndRightClickListener onLeftAndRightClickListener;
//定义一个方法
public void setOnListenter( OnLeftAndRightClickListener onLeftAndRightClickListener){
this.onLeftAndRightClickListener=onLeftAndRightClickListener;
}
//自定义一个借口
public interface OnLeftAndRightClickListener{
void LeftListenter();
void RightListenter();
}
public Top_Bars(Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater.from(context).inflate(R.layout.top_bars,this);
leftButton = findViewById(R.id.leftButton);
rightButton = findViewById(R.id.rightButton);
titletext = findViewById(R.id.titleText);
//创建点击事件
leftButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (onLeftAndRightClickListener!=null){
onLeftAndRightClickListener.LeftListenter();
}
}
});
rightButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (onLeftAndRightClickListener!=null){
onLeftAndRightClickListener.RightListenter();
}
}
});
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.top_bar);
int left_button = typedArray.getResourceId(R.styleable.top_bar_leftbutton, 0);
int right_button = typedArray.getResourceId(R.styleable.top_bar_rightbutton, 0);
String text_title = typedArray.getString(R.styleable.top_bar_text_title);
float text_size = typedArray.getDimension(R.styleable.top_bar_text_size, 0);
int text_color = typedArray.getColor(R.styleable.top_bar_text_color, 0);
typedArray.recycle();
leftButton.setBackgroundResource(left_button);
rightButton.setBackgroundResource(right_button);
titletext.setText(text_title);
titletext.setTextSize(text_size);
titletext.setTextColor(text_color);
}