1

我有一个带有 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 中尝试了“清洁...”。

4

0 回答 0