在 Android 中膨胀后访问自定义视图属性
我有一个带有 LinearLayout 的活动,我想向其中添加多个按钮。这些按钮是我膨胀的自定义视图。我需要在代码中将这些自定义按钮添加到我的线性布局中。所有这些都有效。
我无法开始工作的是在我的自定义按钮膨胀后使用 findViewById 以便我可以设置其属性。 findViewById 返回 null。
活动代码:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.levelbrowser);
LinearLayout uttonLayout = (LinearLayout)findViewById(R.id.ButtonLayout);
LevelBrowserButton button1 = new LevelBrowserButton(this, "Level 1");
ButtonLayout.addView(button1);
}
自定义按钮代码:
public LevelBrowserButton(Context context, String name)
{
super(context);
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.levelbrowser_button, this);
TextView nameTextView = (TextView) layout.findViewById(R.id.NameTextView);
// nameTextView = null!
NameTextView.setText("test"); // This will throw an exception
}
我已经阅读了互联网上的许多帖子,但仍然无法使其正常工作。我还在我的项目中尝试过 Eclipse 中的“Clean...”。
I have an activity with a LinearLayout which I want to add multiple buttons to. These buttons are Custom Views which I inflate. I need to add these custom buttons to my Linear Layout in code. All of this works.
What I cant get to work is to use findViewById in my custom button after I have inflated it so I can set its properties. findViewById returns null.
Activity Code:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.levelbrowser);
LinearLayout uttonLayout = (LinearLayout)findViewById(R.id.ButtonLayout);
LevelBrowserButton button1 = new LevelBrowserButton(this, "Level 1");
ButtonLayout.addView(button1);
}
Custom Button Code:
public LevelBrowserButton(Context context, String name)
{
super(context);
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.levelbrowser_button, this);
TextView nameTextView = (TextView) layout.findViewById(R.id.NameTextView);
// nameTextView = null!
NameTextView.setText("test"); // This will throw an exception
}
I have read through many posts on the internet and still cant get this to work. I have also tried "Clean..." in Eclipse on my project.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论