使用 addContentView 向我的主视图添加一个新的子视图

Adding a new child view to my main view using addContentView

我正在学习一个教程并添加了一个像这样的新视图:

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_display_potential);
    Intent intent = getIntent();
    String message = intent.getStringExtra(MainActivity.EXTRA_NAME);
    TextView textView = new TextView(this);
    textView.setTextSize(40);
    textView.setText(message);

    ViewGroup layout = (ViewGroup) findViewById(R.id.activity_display_potential);
    layout.addView(textView);

但是当我想删除视图并返回主视图时,使用 setContentView 会导致问题。

所以我尝试像这样使用 addContentView:

    super.onCreate(savedInstanceState);
    addContentView(R.layout.activity_display_potential);
    Intent intent = getIntent();
    String message = intent.getStringExtra(MainActivity.EXTRA_NAME);
    TextView textView = new TextView(this);
    textView.setTextSize(40);
    textView.setText(message);

    ViewGroup layout = (ViewGroup) findViewById(R.id.activity_display_potential);
    layout.addView(textView);

我以为这只是一个简单的更改,但我收到了这条消息:

addContentView cannot be applied to int.

addContentView 添加子视图的方法是错误的吗?

这是方法的声明:

addContentView(View view, ViewGroup.LayoutParams params)

可以看出和setContentView不一样。那个只需要设置视图的 id ,例如一个 int。您需要提供实际视图,您可以使用 findViewById 或其他方式获得该视图,以及布局参数。

Very useful thing I learned: Hit CTRL+P (or CMD+P on mac) when you're inside of the brackets of any method and you'll get the parameter list. It will help you see the exact parameter type and order you need to provide for that method.