在Android中充气后访问自定义视图属性

时间:2011-10-06 15:47:47

标签: android view android-inflate

我有一个带有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 ...”。

0 个答案:

没有答案
相关问题