android编程 - 标签不起作用

时间:2013-03-25 18:55:19

标签: android eclipse tabs

我是新用户和初学Android程序员。我在MainActivity.java中编写了一个代码,它不能在虚拟设备上运行,我不知道原因。谁能告诉我为什么它不起作用? 提前谢谢

package com.tee.contactsList;

import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;

public class MainActivity extends Activity
{

    LinearLayout mainLayout;
    TextView title;
    TextView contact1;
    ScrollView scrollList;
    LinearLayout list;
    TabHost tabs;
    TabSpec firstTab;
    TabSpec secondTab;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        tabs = new TabHost(this); 
        firstTab = tabs.newTabSpec("tid1");
        secondTab = tabs.newTabSpec("tid2");
        mainLayout = new LinearLayout(this);
        title = new TextView(this);
        contact1 = new TextView(this);
        scrollList = new ScrollView(this);
        list = new LinearLayout(this);
        tabs.addTab(firstTab);
        tabs.addTab(secondTab);
        firstTab.setIndicator("Contacts");
        secondTab.setIndicator("Calender");
        tabs.getTabWidget().setCurrentTab(1);
        mainLayout.setId(123);
        mainLayout.setOrientation(LinearLayout.VERTICAL);
        list.setOrientation(LinearLayout.VERTICAL);
        mainLayout.addView(title);
        title.setText("Contacts");
        mainLayout.addView(scrollList);
        scrollList.addView(list);
        scrollList.setBackgroundColor(0x0000ff00);
        list.setBackgroundColor(0x0000ff00);
        contact1.setBackgroundColor(0x0000ff00);
        list.addView(contact1);
        String s="\n";
        String array[]={"contact1","contact2","contact3","contact4","contact5"};
        for (int x=0;x<=4;x++)
        {
            s+="contact";
            s+=(x+1);
            s+=":";
            s+=array[x];
            s+="\n";
        }
        contact1.setText(s);
        firstTab.setContent(123);
        setContentView(tabs);
    }   

}

1 个答案:

答案 0 :(得分:0)

您应该将您的布局创建为xml。

在活动中,您引用您在xml中创建的元素的viewID - &gt; findviewbyid

obejcts仅在您的代码中创建,它们不会分配给布局。 例如,setContentView也会发生同样的情况。预计会出现viewID r.layout.xml_file