【问题标题】:How to inflate a layout dynamically?如何动态膨胀布局?
【发布时间】:2011-08-29 13:21:36
【问题描述】:

我在 XML 中定义了以下布局:

<?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/streamRelativeLayout">
        <ListView android:layout_height="fill_parent" android:layout_width="fill_parent" android:id="@+id/streamListView"></ListView>
        <ProgressBar android:layout_centerInParent="true" android:layout_height="wrap_content" android:id="@+id/streamProgressBar" android:layout_width="wrap_content"></ProgressBar>
    </RelativeLayout>

如何使用 LayoutInflater 抓取 ListView 和 ProgressBar 并在代码中分配?

【问题讨论】:

    标签: java android eclipse android-layout layout-inflater


    【解决方案1】:

    这样:

    View v = getLayoutInflater().inflate(R.layout.YOUR_LAYOUT_ID, null);
    ListView listview = (ListView) v.findViewById(R.id.streamListView);
    ProgressBar progress = (ProgressBar) v.findViewById(R.id.streamProgressBar);
    

    【讨论】:

      【解决方案2】:

      您只需要活动引用并调用:

      RelativeLayout relativeLayout = (RelativeLayout)activity.getLayoutInflater().inflate(R.layout.your_layout, null);
      

      然后您可以使用它们的 id 获取两个视图

      relativeLayout.findViewById(R.id.anId);
      

      【讨论】:

      • 我有动态创建的 linaerlayout,即 LinearLayout ll=new LinearLayout(context);这个布局有一些子视图,如 framelayout、webview。现在,我怎样才能膨胀这个线性布局?
      • 避免将 null 作为视图根传递(需要解析膨胀布局的根元素上的布局参数),因为当膨胀布局时,避免将 null 作为父视图传递,否则在膨胀布局的根将被忽略。
      【解决方案3】:
      private LayoutInflater mInflater;
      View convertView;
      mInflater = LayoutInflater.from(context);
      convertView = mInflater.inflate(R.xml.yourxmlname, null);
      

      现在您可以通过

      访问这些项目
      convertView.findViewById
      

      或者如果你有很多实例,你可以定义一个viewholder

      static class CalViewHolder {
          ListView con_list;
          Progressbar con_progress;
      }
      holder = new CalViewHolder();
      convertView.setTag(holder);
      

      【讨论】:

        【解决方案4】:

        试试这个

        RelativeLayout myLayout = (RelativeLayout)getLayoutInflater().inflate(
                        R.layout.you_xml_id, null);
        
                ListView list = (ListView)myLayout.findViewById(R.id.streamListView);
                ProgressBar bar = (ProgressBar)myLayout.findViewById(R.id.streamProgressBar);
        

        【讨论】:

          猜你喜欢
          • 2017-10-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多