【问题标题】:In android Custom View How can i style my Custom View programmatically?在 android 自定义视图中,我如何以编程方式设置自定义视图的样式?
【发布时间】:2016-10-20 18:19:09
【问题描述】:

我有一个 RelativeLayout 的自定义视图“CustomLayout”子类。

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 的参数

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-18
      • 2012-03-12
      • 2011-06-29
      • 2012-08-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多