本文介绍了添加一个按钮,与Java的main_activity视图code的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想添加一个按钮 main_activity 视图用java code,所以我怎么能做到这一点?我已经尝试过这种code和遗憾的是它没有工作

 公共类MainActivity延伸活动{

    按钮BTN;
    @覆盖
    保护无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        RelativeLayout的L1 =((RelativeLayout的)this.findViewById(R.id.view1));
        BTN =新的按钮(这一点);
        btn.setText(R.string.hello_world);
        l1.addView(BTN);
        的setContentView(L1);
    }
}
 

解决方案

由于艾哈迈德说,你不能叫 findViewById 设置内容查看之前。这是因为你的浏览布局中存在,所以你需要一个充气布局发现,在 ID 呼叫的setContentView()先用布局包含视图。然后,你可以找到视图和您的按钮添加到它。

  @覆盖
   保护无效的onCreate(包savedInstanceState)
   {
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.your_layout);
        RelativeLayout的L1 =(RelativeLayout的)findViewById(R.id.view1);
        BTN =新的按钮(这一点);
        btn.setText(R.string.hello_world);
        l1.addView(BTN);
   }
 

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 work

public class MainActivity extends Activity {

    Button btn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        RelativeLayout l1 = ((RelativeLayout)this.findViewById(R.id.view1));
        btn = new Button(this);
        btn.setText(R.string.hello_world);
        l1.addView(btn);
        setContentView(l1);
    }
}
解决方案

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);
   }

这篇关于添加一个按钮,与Java的main_activity视图code的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 06:26