在Android中同时使用XML和编码视图 [英] Using both XML and Coded views in Android

查看:82
本文介绍了在Android中同时使用XML和编码视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在Android OS中同时使用编码视图和xml视图.我希望xml布局保留基本的布局和设置,而我将使用编码视图来创建更多动态部件.

I am trying to use both a coded views and an xml views at the same time in the Android OS. I want the xml layout to hold the basic layout and setup, while I will use coded views to create more dynamic parts.

这是我的设置,我没有收到任何编译错误,但运行时该应用程序崩溃了. Java:

Here's my setup, I receive no compiling errors but the app crashes when ran. The Java:

import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;

public class TopImages extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        LinearLayout layoutContainer = (LinearLayout) this.findViewById(R.id.layout_container);
        TextView tv = new TextView(this);
        layoutContainer.addView(tv);

        setContentView(R.layout.main);
    }
}

XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <LinearLayout 
        android:id="@+id/layout_container" 
        android:layout_width="match_parent" 
        android:layout_height="wrap_content">

    </LinearLayout>

</LinearLayout>

不能同时使用两者吗?

推荐答案

您需要先调用setContentView(R.layout.main);,然后再调用findViewById,因为当前layoutContainer将是null.

You need to call setContentView(R.layout.main); before you call findViewById, as currently layoutContainer will be null.

public class TopImages extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);
        LinearLayout layoutContainer = (LinearLayout) this.findViewById(R.id.layout_container);
        TextView tv = new TextView(this);
        layoutContainer.addView(tv);

    }
}

这篇关于在Android中同时使用XML和编码视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆