2016-10-20 128 views
0

我有一个自定义视图“CustomLayout”的RelativeLayout的子类。在android自定义视图中我如何编程我的自定义视图?

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); 
    ... 
} 

我不知道如何通过传递参数在最后一个构造函数,它有三个参数,从我的活动亲语法设置的属性。我知道从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); 

如何通过含有的AttributeSet在CustomLayout构造函数的参数从这里

回答

1

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