【问题标题】:getLayoutInflater().inflate() in a loop always returns the first view循环中的 getLayoutInflater().inflate() 总是返回第一个视图
【发布时间】:2016-08-22 10:15:31
【问题描述】:

tics 有 3 个项目。以下代码创建了 3 个工单项目,但始终设置第一个工单的 TextViews 的文本。

public void onSuccess(int i, Header[] headers, byte[] bytes) {
                    progress.dismiss();
                    String response = new String(bytes);
                    try{
                        JSONObject obj = new JSONObject(response);
                        JSONArray tics = obj.getJSONArray("tickets");
                        LinearLayout p = (LinearLayout)findViewById(R.id.tickets);

                        for(int j = 0;j<tics.length();j++){
                         LinearLayout t =(LinearLayout) getLayoutInflater().inflate(R.layout.ticket_row, p);
                            TextView topic = (TextView)t.findViewWithTag("topic");
                            TextView section = (TextView)t.findViewWithTag("section");
                            TextView datetime = (TextView)t.findViewWithTag("datetime");
                            JSONObject item = tics.getJSONObject(j);
                            Toast.makeText(getApplicationContext(),item.getString("Caption") ,Toast.LENGTH_LONG).show();
                            topic.setText(item.getString("Caption"));
                            datetime.setText(item.getString("DateString"));
                            section.setText(item.getString("Section"));
                        }
                    }catch (Exception e){}
                }

在以下代码中:

 LinearLayout t =(LinearLayout) getLayoutInflater().inflate(R.layout.ticket_row, p);

t不应该是膨胀的View吗?

【问题讨论】:

    标签: java android android-studio layout-inflater


    【解决方案1】:

    不应该是膨胀的View吗?

    不,您使用的版本将膨胀视图添加到父级并返回父级本身。你可以使用

    View inflate (XmlPullParser parser, 
                    ViewGroup root, 
                    boolean attachToRoot)
    

    提供 false 作为第三个参数。这样 android 将返回膨胀的视图(父级将仅用于布局参数)。您必须手动将其添加到父级。

    【讨论】:

    • 视图不会被添加到父级。我应该使用p.addView(t); 对吗?
    猜你喜欢
    • 1970-01-01
    • 2017-11-16
    • 1970-01-01
    • 1970-01-01
    • 2021-06-17
    • 1970-01-01
    • 2021-06-22
    • 2011-04-08
    • 1970-01-01
    相关资源
    最近更新 更多