【问题标题】:Create own custom View without using XML在不使用 XML 的情况下创建自己的自定义视图
【发布时间】:2010-10-04 22:40:39
【问题描述】:

我想创建一个包含两个按钮而不使用 xml 的自定义视图。

我试过了:

public class ZoomPlate extends LinearLayout {

    private Context context;

    private Button plus;
    private Button minus;

    public ZoomPlate(Context context) {
        super(context);
        init(context);

    }

    public ZoomPlate(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    private void init(Context context) {
        this.context = context;     

        LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT,0);

        plus = new Button(context);
        plus.setText("Plus");
        plus.setLayoutParams(params);

        minus = new Button(context);
        minus.setText("Minus");
        minus.setLayoutParams(params);

        setOrientation(LinearLayout.VERTICAL);


        addView(plus);
        addView(minus);
    }
}

这样我就可以在 XML 中使用 ZoomPlate,就像一个按钮或一个 textview 一样:

<at.bartinger.zoomplate.ZoomPlate
    android:id="@+id/zoomplate"
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" />

但是当我尝试这个时,什么都没有显示

【问题讨论】:

    标签: java android xml view


    【解决方案1】:

    这可能与您在主 Activity 中设置的内容视图有关吗?在这里检查: http://developer.android.com/reference/android/app/Activity.html#setContentView%28int%29

    基本上你必须从布局资源或视图中设置它。

    【讨论】:

      【解决方案2】:

      如何将自定义视图添加到 XML 布局中?您需要使用完整的包名,如&lt;com.blabla.bla.ViewName android:properties="whatever" /&gt;

      【讨论】:

      • 是的,我知道如何在 xml 中编写它。问题是 Viewobject
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-08-02
      • 2021-11-21
      • 2023-04-07
      • 1970-01-01
      • 2013-02-10
      • 1970-01-01
      • 2014-09-30
      相关资源
      最近更新 更多