package scg.cgg.com.titleactivitydemo; import android.content.Context; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.widget.RadioButton; import android.widget.RelativeLayout; import android.widget.TextView; public class MyTopBar extends RelativeLayout { private TopBarListener topBarListener; // 定义个接口 public interface TopBarListener { public void leftListener(); public void rightListener(); } public MyTopBar(Context context) { this(context,null); } public MyTopBar(Context context, @Nullable AttributeSet attrs) { this(context, attrs,0); } public MyTopBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); // 实例化子控件 RadioButton leftButton = new RadioButton(context); RadioButton rightButton = new RadioButton(context); TextView title = new TextView(context); // 初始化控件 leftButton.setText("< back"); rightButton.setText("commit"); title.setText("Title"); title.setTextSize(26); // 声明空的Bitmap对象 Bitmap a = null; // 去掉单选框的小圈圈 leftButton.setButtonDrawable(new BitmapDrawable(a)); // 设置字体大小 leftButton.setTextSize(20); rightButton.setButtonDrawable(new BitmapDrawable(a)); rightButton.setTextSize(20); // 部署子控件的显示位置 RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT); RelativeLayout.LayoutParams layoutParams1 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); layoutParams1.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); RelativeLayout.LayoutParams layoutParams2 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); layoutParams2.addRule(RelativeLayout.CENTER_IN_PARENT); // 将属性部署到子控件中 leftButton.setLayoutParams(layoutParams); rightButton.setLayoutParams(layoutParams1); title.setLayoutParams(layoutParams2); // 将子控件加入到父控件中 addView(leftButton); addView(rightButton); addView(title); // 控件的点击事件 leftButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { // 调用接口中的方法 if(topBarListener!=null)topBarListener.leftListener(); } }); rightButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { if(topBarListener!=null)topBarListener.rightListener(); } }); } // 暴露一个共有的方法去实现TopBarListener接口 public void setOnTopBarClickListener(TopBarListener listener){ this.topBarListener = listener; } }
android自定义标题栏
最新推荐文章于 2022-03-31 22:09:34 发布