2016-10-20 149 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));