【问题标题】:Where should I put the function setContentView()?我应该把函数 setContentView() 放在哪里?
【发布时间】:2016-11-09 10:18:58
【问题描述】:

我知道函数 onCreate() 用于构造活动和 UI 组件,但是当我尝试将 setContentView(R.layout.activity_main) 放入函数 onStart() 或 onResume() 时,UI 组件出现了,这就是为什么?

package com.example.E001;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;


public class MainActivity extends Activity {

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

    protected void onStart() {
        super.onStart();
        setContentView(R.layout.activity_main);
        //setContentView(R.layout.demo);  
        Button btn_welcome = (Button)this.findViewById(R.id.welcome_msg);
        btn_welcome.setText(R.string.hello_world);
    }
}

【问题讨论】:

    标签: android put setcontentview


    【解决方案1】:

    你应该把它放在onCreate中,像这样:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
     }
    

    更多信息请查看Android Documentation

    我认为您尝试对 layout.demo 执行的操作是在 MainActivity 中增加一个额外的视图。 那么你不应该使用 setContentView()。要在布局中扩展视图,您可以使用 LayoutInflater

    注意:如果这不能完全回答您的问题,那么我没有正确理解您的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-30
      • 2016-08-25
      • 2013-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-23
      • 2010-12-24
      相关资源
      最近更新 更多