【问题标题】:Android : How to load an activity faster when calling it from another activity, even while loading several contents in the second activityAndroid:如何在从另一个活动调用它时更快地加载一个活动,即使在第二个活动中加载多个内容时
【发布时间】:2017-08-18 04:49:06
【问题描述】:

我是 java 和 android 的新手,所以我在这里问这些问题以了解它应该如何工作。

我的应用中有 2 个活动,即 Welcome_Activity.javaContent_Activity.java

第一个 Activity 工作顺利,但是当从 Welcome_Activity(First Activity) 调用 Content_Activity(Second Activity) 时问题就来了

Second ActivityonCreate中,我认为内容太多会导致Activity加载太慢。

如何解决这个问题?

例子:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_Puzzle_game);

    q1_tv = (TextView) findViewById(R.id.q1_tv);
    q2_tv = (TextView) findViewById(R.id.q2_tv);
    q3_tv = (TextView) findViewById(R.id.q3_tv);
    q4_tv = (TextView) findViewById(R.id.q4_tv);
    q5_tv = (TextView) findViewById(R.id.q5_tv);
    q6_tv = (TextView) findViewById(R.id.q6_tv);
    q7_tv = (TextView) findViewById(R.id.q7_tv);
    q8_tv = (TextView) findViewById(R.id.q8_tv);
    q9_tv = (TextView) findViewById(R.id.q9_tv);
    q10_tv = (TextView) findViewById(R.id.q10_tv);

    bt1 = (Button) findViewById(R.id.bt1);
    bt2 = (Button) findViewById(R.id.bt2);
    bt3 = (Button) findViewById(R.id.bt3);
    bt4 = (Button) findViewById(R.id.bt4);
    bt5 = (Button) findViewById(R.id.bt5);
    bt6 = (Button) findViewById(R.id.bt6);
    bt7 = (Button) findViewById(R.id.bt7);
    bt8 = (Button) findViewById(R.id.bt8);
    bt9 = (Button) findViewById(R.id.bt9);
    bt10 = (Button) findViewById(R.id.bt10);

    SP = getSharedPreferences("saved_data", MODE_PRIVATE);
    solved = SP.getInt("solved", 0);

    // LoadLevel & ResumeGame is just a method to get data from another class that have array Strings to fill the textviews and buttons 

    if (solved > 0) {
        ResumeGame(null);
    }
    else {
        LoadLevel(null);
    }
}

【问题讨论】:

  • 为什么 content_activity 很慢?你在使用网络服务还是什么?
  • 您能否解释一下您试图在 Content_Activity 中加载哪种数据导致加载缓慢?
  • 请分享创建代码
  • 您能否提供onCreate 的代码用于慢速活动?你想在那边做什么?
  • 你有没有尝试在后台线程而不是ui线程中准备需求数据?

标签: java android oncreate


【解决方案1】:

我假设您正在从 Web 服务或本地应用程序存储中获取 ResumeGameLoadGame 方法中的数据;如果是这样,请尝试在主线程(UI 线程)以外的地方进行获取操作,并且一旦获得数据,请尝试在 UI 线程上传递此数据。为你(初学者)做这件事的最好方法是使用AsyncTaskAsyncTask 中可用的回调可能是:

  • doInBackground:这里写你的代码来获取数据
  • onPostExecute:在这里你可以填写你的 UI 视图,比如按钮标签,TextView 的文本

我希望这将有助于您提高性能。

【讨论】:

  • 它只是一个名为“questions”的类,每个级别都有字符串数组..所以我从一个类加载数据,我只需从该类内的数组中选择 10 个元素
  • 如果您没有使用任何数据操作/获取,我猜是您的布局需要时间来呈现。您应该查看您的布局文件并通过使用较少数量的容器来优化布局。
  • 可能是这样,我想我会尝试启动画面,非常感谢 Anshuman
【解决方案2】:

你应该看看Asyntask。它通过在后台线程中执行来帮助您加载/执行需要一些时间的任务。这将有助于您的 Activity(UI) 不会生涩。

【讨论】:

  • 得对这个 Asyntask 做一些研究,因为我提到我是一个初学者..所以 XD 非常感谢男人
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-26
  • 1970-01-01
  • 2018-03-24
相关资源
最近更新 更多