Android动态添加视图的方法示例

  

由于项目需求菜单写活,效果如下:

  

 Android动态添加视图的方法示例

  

这里的按钮数量是可变的png

  

由于不是可滑动控件,我用的百分比布局做的适配

        LinearLayout typeLayout=(LinearLayout) headerView.findViewById (R.id.layout_type);   最后ListfirstTypeList=entity.getData ();   for (int i=0; i< firstTypeList.size();我+ +){   WindowManager wm=(WindowManager) getContext ()   .getSystemService (Context.WINDOW_SERVICE);   .getWidth int宽度=wm.getDefaultDisplay () ();   .getHeight int高度=wm.getDefaultDisplay () ();   视图视图=View.inflate (getActivity (), R.layout.item_first_type, null);   LinearLayout标签=(LinearLayout) view.findViewById (R.id.tab);   LinearLayout。LayoutParams linearParams=(LinearLayout.LayoutParams) tab.getLayoutParams ();   linearParams。宽度=宽/firstTypeList.size();//根据数量来吧   linearParams。身高=宽/firstTypeList.size();//根据数量来吧   tab.setLayoutParams (linearParams);//使设置好的布局参数应用到控件   }   之前      

item_first_type代码:

        & lt; com.zhy.android.percent.support.PercentLinearLayout   android: id=癅 + id/选项卡”   android: layout_width=" match_parent "   android: layout_height=" match_parent "   android:取向=按怪薄?   android:重力="中心"   android:背景=癅drawable/selector_choose_white”比;   & lt; ImageView   android: id=癅 + id/iv”   android: layout_width=" 0 dp”   应用:layout_widthPercent=?5% h”   android: layout_height=" 0 dp”   应用:layout_heightPercent=?5% h”   android: src=" https://www.yisu.com/zixun/@mipmap first_newenergy_tab "/比;   & lt; TextView   android: id=癅 + id/电视”   android: layout_width=" match_parent "   android: layout_height=" 0 dp”   应用:layout_heightPercent=?0% h”   android:文本="新能源”   android:输入textColor=" @color/black_my”   应用:layout_textSizePercent=?2%”   android:重力="中心"   android: maxLines=" 1 "   android: ellipsize="结束"/比;   & lt;/com.zhy.android.percent.support.PercentLinearLayout>   之前      

layout_type代码:

        & lt; com.zhy.android.percent.support.PercentLinearLayout   android: id=癅 + id/layout_type”   android: layout_width=" match_parent "   android: layout_height=" wrap_content "   面向android:="水平"   android:背景=" @color/白”比;   & lt;/com.zhy.android.percent.support.PercentLinearLayout>   之前      

这种写法数量一般3 - 6个还是可以的,如果太多的话还是推荐用RecyclerView。
  

  

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

Android动态添加视图的方法示例