简体   繁体   English

XML布局与视图的setContentView()

[英]setContentView() with XML layout vs View

In Android, I'm used to setting layouts with the XML file 在Android中,我习惯于使用XML文件设置布局

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

But you can also set the content using a View in Java 但是您也可以使用Java中的View设置内容

    // Create the text view
    TextView textView = new TextView(this);
    textView.setTextSize(40);
    textView.setText(message);

    // Set the text view as the activity layout
    setContentView(textView);

This has the side effect of not being able to use the layout file any more. 这具有不能再使用布局文件的副作用。

Is there anyway I can programatically set, for example, a text value and still use the layout.xml file? 无论如何,我可以通过编程方式设置一个文本值,例如仍然使用layout.xml文件吗?

Sure. 当然。

In your layout.xml file you must define an id of the main layout (android:id="@+id/mainLayout" ) and then you can do this: 在您的layout.xml文件中,您必须定义main layoutid (android:id="@+id/mainLayout" ) ,然后可以执行以下操作:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ViewGroup mainView = (ViewGroup) findViewById(R.id.mainLayout);

    // Create the text view
    TextView textView = new TextView(this);
    textView.setTextSize(40);
    textView.setText(message);

    mainView.addView(textView);
}

When you use setContentView(R.layout.activity_main), you are telling that the layout to be used is the xml layout file activity_main. 当您使用setContentView(R.layout.activity_main)时,您在说要使用的布局是xml布局文件activity_main。

When you use setContentView(textView), it replaces the previous added xml layout file by the textView component. 使用setContentView(textView)时,它将由textView组件替换之前添加的xml布局文件。

You can declare your TextView in the layout file and then set the text programmatically. 您可以在布局文件中声明TextView,然后以编程方式设置文本。

TextView textView = (TextView) findViewById(R.id.textView);
textView.setTextSize(40);
textView.setText(message);

for example: 例如:

in layout.xml paste this code: 在layout.xml中粘贴以下代码:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id = "@+id/lblText"
        android:textSize="40"
        />

</RelativeLayout>

and, in you MainActivity : 并且,在您的MainActivity中:

public class MainActivity extends Activity 
{

    private TextView lblText;

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

        this.lblText = (TextView)findViewById(R.id.lblText);
        this.lblText.setText("your message");        
    }
}

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

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