开发者

Access custom view properties after inflation in Android

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 LevelBrowserB开发者_如何学Cutton(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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜