如何在onCreate()方法中显示MainActivity的布局?

时间:2015-11-29 15:50:18

标签: android

我刚刚开始研究android,并且对屏幕上的绘图布局感到困惑。 我想做的是,

1>显示MainActivity的布局 - 在xml布局文件中设计

2 - ;等待2秒,仍然显示MainActivity

3>转到下一个活动

根据我最近的代码,它只显示白色空白屏幕2秒,然后显示下一个活动。

这是我目前的MainActivity源代码。

public class MainActivity extends AppCompatActivity {
    Intent settingIntent;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    protected void onStart(){
        super.onStart();
        try {
            Thread.sleep(2000);
        } catch(InterruptedException e) {
            //
        }
        settingIntent = new Intent(this,SettingActivity.class);
        startActivity(settingIntent);
    }
}

如何按照我的意图使这项工作?

3 个答案:

答案 0 :(得分:4)

您可以使用View s - postDelayd

的默认方法
findViewById(android.R.id.content).postDelayed(new Runnable() {
        @Override
        public void run() {
            Intent settingIntent = new Intent(MainActivity.this, SettingActivity.class);
            MainActivity.this.startActivity(settingIntent);
        }
    }, 2000);

之后写下来
setContentView(R.layout.activity_main);

并删除onStart

答案 1 :(得分:2)

当你打电话给睡眠时,你会暂停UI线程。这不是你追求的目标。而是这样做:

import csv
import matplotlib.pyplot as plt

f = open('2014.csv', 'rb')
try:
reader = csv.reader(f)

avgK = 0
avgD = 0
date = 0
mon = 1
avergK = []
avergD = []
count_date = 1

for row in reader:
    if row[2] == 'TAVG':
        count_date +=1
        date = (int(row[1]) % 10000)

        if row[0] == 'UPM00033345':    
            avgK += float(row[3])/10.0

        elif row[0] == 'UPM00034504':
            avgD += float(row[3])/10.0

    if (date//100 > mon):
        print date //100, mon, date%100, avgK, avgD
        avergK.append(avgK/count_date)
        avergD.append(avgD/count_date)
        mon += 1
        avgK = 0
        avgD = 0
        count_date = 1
        continue
finally:
    f.close()

plt.subplot(2, 1, 1)
plt.plot(avergK)
plt.xlabel('Month')
plt.ylabel('Average Temperature')
plt.title('AVG in Kiev 2014')
plt.grid(True)

plt.subplot(2, 1, 2)
plt.plot(avergD)
plt.xlabel('Month')
plt.ylabel('Average Temperature')
plt.title('AVG in DNIPROPETROVSK 2014')
plt.grid(True)

plt.show()

修改

正如Commonsware正确指出的那样,这有可能引入内存泄漏。你应该考虑使用@yidavewu发布的解决方案。

答案 2 :(得分:0)

我所知道的onStart回调告诉我们即将展示活动性。 所以它还没有显示出来。更好的选择是将您的代码用于在onResume回调中显示新活动。