【问题标题】:Android activity getting halt during loop with inflatorAndroid 活动在充气机循环期间停止
【发布时间】:2015-08-11 09:48:16
【问题描述】:

我的代码运行良好。但问题是在我从网络服务收到数据之后。当我启动循环以创建多行时,我的活动会暂停 5 到 10 秒。可以从服务中接收的最大记录不超过 100。

我该如何解决这个问题?在不停止我的活动的情况下它应该生成多条记录。因为我已经有几条记录要迭代了。

LinearLayout parentLayout = (LinearLayout)findViewById(R.id.sheet);
LayoutInflater layoutInflater = getLayoutInflater();
View view;
JSONArray receivedData = (JSONArray) json.get("RESPONSE_DATA");
for(int i=0; i<receivedData.length(); i++){
    view = layoutInflater.inflate(R.layout.row, parentLayout, false);
    ((TextView)view.findViewById(R.id.title1)).setText( (((JSONObject)receivedData.getJSONObject(i)).get("title1")).toString() );
    ((TextView)view.findViewById(R.id.title2)).setText( (((JSONObject)receivedData.getJSONObject(i)).get("title2")).toString() );
    ToggleButton button = (ToggleButton)view.findViewById(R.id.button);
    button.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            View parentView = (View)buttonView.getParent();
            if(isChecked){
                parentView.setBackgroundColor(0x00000000);
            }else{
                parentView.setBackgroundColor(0xffDF9292);
            }
        }
    });
    parentLayout.addView(view);
}

【问题讨论】:

    标签: android android-activity layout-inflater


    【解决方案1】:

    这里是使用适配器的好地方。 有关详细信息,请参阅 Android 开发者的this link

    您的活动可能会停止,因为您在 UI 线程上做了太多工作。我还可以想象,由于目前有太多 UI 对象处于活动状态,它会变得迟钝。当您使用带有适配器的列表时,所有这些都会得到解决。

    [编辑]

    我认为this tutorial from Vogella 可能是一个更好的起点。

    【讨论】:

    • 感谢@MatBos Seconds 链接更有用
    【解决方案2】:

    活动停止,因为您正在主活动线程上运行代码。我建议您使用异步的东西,尝试在AsyncTask 中实现您的代码(但在 onPostExecute 中附加视图)。 另一种方法是添加 ListView 并使用自定义 ArrayAdapter this is an example 加载数据。

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-17
      • 1970-01-01
      • 2021-03-21
      • 1970-01-01
      • 2014-01-26
      • 1970-01-01
      相关资源
      最近更新 更多