【问题标题】:Android - Call an xml layout file in a class that extends ViewAndroid - 在扩展 View 的类中调用 xml 布局文件
【发布时间】:2012-03-22 11:03:54
【问题描述】:

我想在扩展视图的类中调用我的 XML 布局文件。我无法在其中执行 oncreate 功能,因为它不扩展 Activity。我的事件在一个类文件中,我在另一个类文件中调用该类;但我想在 XML 布局文件上执行这些事件。

这是我的代码:

Demo.java

public class Demo extends Activity
{
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new another(this));
}

另一个.java

public class another extends View
{
      public anotherView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        init();
    }

    public anotherView(Context context) {
        super(context);
        init();
    }

    public anotherView(Context context, AttributeSet attrs) {
        super(context, attrs);  

        init();
    }

    private void init() {
        setWillNotDraw(false);
       ...
        ..
        ..
}

还有 XML 文件

abc.xml
..
..

怎么做?

【问题讨论】:

  • 你希望你的类可以像 android 视图一样在 XML 中使用吗?

标签: android android-view android-event


【解决方案1】:

如果您想将一个项目添加到您的视图中,您可以随时对其进行充气。

LayoutInflater inflater = (LayoutInflater)    
getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

View view = inflater.inflate(R.layout.ABC, null);
addView(view);

【讨论】:

    【解决方案2】:

    如果您想要从 XML 中获取项目 您应该致电
    [yourviewType]View v1 = (Cast-to-type-of-view)context.findViewById(R.id.idOfView);

    示例: TextView tv1 = (TextView)findViewById(R.id.aboutText);

    这是你需要的吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-27
      相关资源
      最近更新 更多