/定义布局为RelativeLayout的xml 改为extends elativeLayout public class Mytitle extends LinearLayout { //定义全局的上下文 private Context mcontent; public Mytitle(Context context) { this(context,null); } public Mytitle(Context context, AttributeSet attrs) { this(context, attrs,0); } public Mytitle(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); //给全局上下文赋值 mcontent=context; //找到自己定义的xml布局文件 LayoutInflater inflater = LayoutInflater.from(context); View view = inflater.inflate(R.layout.my_title, this, true); //找到控件 TextView fan = view.findViewById(R.id.fan); //给控件设置点击事件 fan.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { Toast.makeText(mcontent,"你点击了返回键",Toast.LENGTH_SHORT).show(); } }); } }//引用直接打类名会有提示
<com.example.rikao1229.Mytitle android:layout_width="match_parent" android:layout_height="wrap_content"></com.example.rikao1229.Mytitle>
自定义xml布局
最新推荐文章于 2024-06-26 21:36:35 发布