简体   繁体   English

setContentView如何在Android中工作?

[英]How does setContentView work in android?

I am trying to display a button on my android app but everytime i run the app it crashes. 我试图在我的android应用程序上显示一个按钮,但是每次我运行该应用程序时,它都会崩溃。 i realise this is because i use setContentView multiple times? 我意识到这是因为我多次使用setContentView吗? I dont understand how it works, and dont understand how i can fix this problem so my button will display. 我不明白它是如何工作的,也不知道我该如何解决这个问题,这样我的按钮才会显示。 my code is below. 我的代码如下。

public class MainActivity extends Activity {
    Draw draw;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        draw = new Draw(this);
        draw.setBackgroundColor(Color.BLUE);
        setContentView(draw);

        LinearLayout l = new LinearLayout(this);
        l.setOrientation(LinearLayout.VERTICAL);
        setContentView(l);
        l.addView(new Draw(this));
        //setContentView(R.layout.activity_main);



        setUpBlockBtn();
    }

    private void setUpBlockBtn(){
        setContentView(R.layout.activity_main);
        Button addBlockButton = (Button)findViewById(R.id.btnBlock);

        addBlockButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i("DemoButtonApp", "you clicked the button");
                //finish();
            }
        });
    }

You try to access Button from android xml layout but you do not set this layout in Activity. 您尝试从android xml布局访问Button,但未在Activity中设置此布局。

Put you button activity_main.xml and use this button in your activity. 将您的按钮置于activity_main.xml中,并在您的活动中使用此按钮。

Thanks 谢谢

You can create one more layout and add Draw and Linear layout to that layout. 您可以再创建一个布局,然后将“绘图”和“线性”布局添加到该布局。

Something like this. 这样的事情。

LinearLayout l1=new LinearLayout(this);
l1.setOrientation(LinearLayout.VERTICAL);

l1.addView(draw);
l1.addView(l2)   // your linearLayout.

setContentView(l1)

Remember you can't use setContentView more than one time. 请记住,您不能多次使用setContentView。 There should be top layout which includes subview and other layouts and then you can add that layout to your activity. 应该有包括子视图和其他布局的顶部布局,然后您可以将该布局添加到活动中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM