在Android自定义视图中如何以编程方式设置自定义视图的样式?

时间:2016-10-20 09:50:33

标签: android android-layout android-custom-view

我有自定义视图" CustomLayout" RelativeLayout的子类。

public class CustomLayout extends RelativeLayout implements View.OnClickListener{
private String titleText;
private Context context;
private AttributeSet attrs;
private ImageView iv1,iv2;
private TextView title,tv2;
private TextView textView;
private Button button;


public CustomLayout(Context context) {
    this(context, null);
}
public CustomLayout(Context context, AttributeSet attrs) {
    super(context, attrs);
    this.context = context;
    this.attrs = attrs;
    init();

}
public CustomLayout(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    this.context = context;
    this.attrs = attrs;
    initAttributes(context,attrs,defStyle);
}
 private void initAttributes(Context context, AttributeSet attrs, int defStyleAttr) {
    // declare styleable here to programatically set custom view style attributes
    final int[] styleable = new int[] {
            android.R.attr.src,
            android.R.attr.textAppearance,
            android.R.attr.text,
            android.R.attr.textSize
    };
    Arrays.sort(styleable);

    TypedArray a = context.obtainStyledAttributes(attrs, styleable, defStyleAttr,0);
    ...
}

我不知道如何通过在我的Activity中的最后一个构造函数中传递参数来进行编程方式设置属性,该构造函数包含三个参数。我知道要从layout.xml文件中执行此操作,如下面的代码所示。请帮助

 <com.example.customview.CustomLayout
    android:id="@+id/view1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="?android:selectableItemBackground"
    app:titleText="HappyTrips Editors"
    app:descriptText="@string/content"
    app:titleTextColor="#FF0000"
    app:descriptTextColor="#0000FF"
    app:titleTextSize="8sp"
    app:descriptTextSize="6sp"
    app:bgColor="#FFFF00"/>

在我的ListAdapter中

 @Override
public View getView(final int position, View convertView, ViewGroup parent) {
    View result=convertView;
    if (convertView==null){
        result=inflater.inflate(R.layout.layout_list_items,null);
        CustomLayout object = (CustomLayout)result.findViewById(R.id.view1);

如何从CustomLayout构造函数中传递包含AttributeSet的参数

1 个答案:

答案 0 :(得分:2)

在layout.xml中你可以用户样式,它会工作或 CustomLayout object = new CustomLayout(new ContextThemeWrapper(this,R.style,customStyle));