Android自定義控制元件並且使其可以在xml中自定義屬性
阿新 • • 發佈:2019-02-13
下面的xml表明如何在xml中配置自定義屬性:package org.xiaom.customView.view; import org.xiaom.customView.R; public class MyView extends LinearLayout { private View root = null; // 上面的img private ImageView imgView = null; // img下面的text private TextView txtView = null; // 上面的影象資源Id Drawable img; // 文字內容 String text; public MyView(Context context, AttributeSet attrs) { super(context, attrs); TypedArray ta = context.obtainStyledAttributes(attrs,R.styleable.myView); img = ta.getDrawable(R.styleable.myView_img); text = ta.getString(R.styleable.myView_text); initView(context); //記得此處要recycle(); ta.recycle(); } private void initView(Context context) { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); root = inflater.inflate(R.layout.view_my_view, this, true); imgView = (ImageView) root.findViewById(R.id.img); txtView = (TextView) root.findViewById(R.id.txt); //將自定義屬性的值傳遞給對應View imgView.setBackgroundResource(R.drawable.icon_consultation); txtView.setText(text); } }