【问题标题】:Android: how to make findViewById(R.id.xxx) working in a class inheriting/extending from the View class?Android:如何使 findViewById(R.id.xxx) 在从 View 类继承/扩展的类中工作?
【发布时间】:2011-10-11 10:21:28
【问题描述】:

我有以下问题:我想在我的主要活动中添加一个自定义视图(custom_view.xml 和关联的 CustomView.java 类)。

所以,我做了以下事情:

1) 在我的主要活动中(链接到 main.xml):

CustomView customView = new CustomView(this);
mainView.addView(customView);

2) 在我的 CustomView.java 类中(我想链接到 custom_view.xml):

public class CustomView extends View {

public CustomView(Context context)
{
super(context);

/* setContentView(R.layout.custom_view); This doesn't work here as I am in a class extending from and not from Activity */

TextView aTextView = (TextView) findViewById(R.id.aTextView); // returns null

///etc....
}

}

我的问题是 aTextView 仍然等于 null... 这显然是因为我的 custom_view.xml 没有链接到我的 CustomView.java 类。我该怎么做这个链接?确实,我试过 setContentView(R.layout.custom_view);但它不起作用(编译错误),因为我的类是从 View 类而不是 Activity 类扩展的。

感谢您的帮助!!

【问题讨论】:

  • 你不应该在某个时候夸大你的 xml 吗?
  • 谢谢 njzk2。看来我应该夸大我的xml。我怎样才能做到这一点 ? (感谢您的回答,以防我找不到有关此主题的任何博客)

标签: android class view android-activity


【解决方案1】:

如果我理解正确,您正在尝试从 layoutfile(R.layout.custom_view) 构建 customview。您想从该布局文件中找到一个文本视图。那正确吗?

如果是这样,您需要使用您拥有的上下文来扩充布局文件。然后你可以从布局文件中找到文本视图。

试试这个。

LayoutInflater inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.custom_view, null);
TextView aTextView = (TextView) v.findViewById(R.id.aTextView);

【讨论】:

    【解决方案2】:

    我建议你试试这个:

    TextView aTextView = (TextView) ((Activity)this.getContext()).findViewById(R.id.aTextView);
    

    它对我有用!!!

    【讨论】:

      【解决方案3】:

      尝试膨胀 customView。

      其次,尝试(我假设aTextView id存在于CustomView侧)

      TextView aTextView = (TextView) mainView.findViewById(R.id.aTextView);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-06-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多