Add a button to the main_activity view with Java code

后端 未结 1 1806
無奈伤痛
無奈伤痛 2021-01-29 09:53

I want to add a Button to the main_activity view using java code , so how can i do it ? I have already tried this code and unfortunately it didn\'t wor

相关标签:
1条回答
  • 2021-01-29 10:23

    As Ahmad has said, "You can't call findViewById before setting the contentView". This is because your Views exist within your layout so you need an inflated layout to find the id in. Call setContentView() first with the layout which contains view. Then you can find the view and add your Button to it.

       @Override
       protected void onCreate(Bundle savedInstanceState) 
       {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.your_layout);
            RelativeLayout l1 = (RelativeLayout) findViewById(R.id.view1);
            btn = new Button(this);
            btn.setText(R.string.hello_world);
            l1.addView(btn);
       }
    
    0 讨论(0)
提交回复
热议问题