public class TitleView extends LinearLayout implements View.OnClickListener{ private TypedArray typedArray; private String btnleft; private String btnright; private String btntitle; private View inflate; private Button leftid; private Button rightid; private TextView titleid; public TitleView(Context context) { super(context); } public TitleView(Context context,AttributeSet attrs) { this(context, attrs,0); } public TitleView(Context context,AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); typedArray = context.getTheme().obtainStyledAttributes(attrs, R.styleable.TitleView, 0, 0); btnleft = typedArray.getString(R.styleable.TitleView_leftbtn); btnright = typedArray.getString(R.styleable.TitleView_rightbtn); btntitle = typedArray.getString(R.styleable.TitleView_titlebtn); inflate = inflate(context, R.layout.title_layout, this); leftid = inflate.findViewById(R.id.left_btn); rightid = inflate.findViewById(R.id.right_btn); titleid = inflate.findViewById(R.id.title_tv); leftid.setOnClickListener(this); rightid.setOnClickListener(this); titleid.setOnClickListener(this); leftid.setText(btnleft); rightid.setText(btnright); titleid.setText(btntitle); } @Override public void onClick(View view) { switch (view.getId()){ case R.id.left_btn: onClick.onleft(); break; case R.id.right_btn: onClick.onright(); break; case R.id.title_tv: onClick.ontitle(); break; } } onClick onClick; public interface onClick{ void onleft(); void onright(); void ontitle(); } public void setOnchlick(onClick onchlick){ this.onClick=onchlick; } }
<resources> <declare-styleable name="TitleView"> <attr name="leftbtn" format="string"/> <attr name="rightbtn" format="string"/> <attr name="titlebtn" format="string"/> </declare-styleable> </resources>
titleView = findViewById(R.id.main_title); flowss = findViewById(R.id.main_flow); titleView.setOnchlick(new TitleView.onClick() { @Override public void onleft() { Toast.makeText(MainActivity.this,"加一",Toast.LENGTH_SHORT).show(); TextView textView=new TextView(MainActivity.this); textView.setText("加一个"); textView.setGravity(Gravity.CENTER); textView.setTextSize(20); textView.setBackgroundColor(Color.RED); textView.setWidth(flowss.getWidth()/2); textView.setHeight(30); flowss.addView(textView); } @Override public void onright() { boolean b; if (flowss.getChildAt(0)!=null){ b=true; }else{ b=false; } if (b){ flowss.removeViewAt(0); } flowss.removeViewAt(0); } @Override public void ontitle() { flowss.removeAllViews(); } });