当前位置: 移动技术网 > IT编程>移动开发>Android > Android动态添加view的方法示例

Android动态添加view的方法示例

2019年07月24日  | 移动技术网IT编程  | 我要评论

3月节日,月光沙滩,舞狮人

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

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

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

 linearlayout typelayout = (linearlayout) headerview.findviewbyid(r.id.layout_type);
 final list<firsttypeentity.databean> firsttypelist = entity.getdata();
 for (int i = 0;i<firsttypelist.size();i++){
    windowmanager wm = (windowmanager) getcontext()
        .getsystemservice(context.window_service);
    int width = wm.getdefaultdisplay().getwidth();
    int height = wm.getdefaultdisplay().getheight();
    view view = view.inflate(getactivity(),r.layout.item_first_type,null);
    linearlayout tab = (linearlayout) view.findviewbyid(r.id.tab);
    linearlayout.layoutparams linearparams =(linearlayout.layoutparams) tab.getlayoutparams(); 
    linearparams.width = width/firsttypelist.size();//根据数量来吧
    linearparams.height = width/firsttypelist.size();//根据数量来吧
    tab.setlayoutparams(linearparams); //使设置好的布局参数应用到控件
 }

item_first_type代码:

<com.zhy.android.percent.support.percentlinearlayout
    android:id="@+id/tab"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    android:background="@drawable/selector_choose_white">
    <imageview
      android:id="@+id/iv"
      android:layout_width="0dp"
      app:layout_widthpercent="45%h"
      android:layout_height="0dp"
      app:layout_heightpercent="45%h"
      android:src="@mipmap/first_newenergy_tab"/>
    <textview
      android:id="@+id/tv"
      android:layout_width="match_parent"
      android:layout_height="0dp"
      app:layout_heightpercent="20%h"
      android:text="新能源"
      android:textcolor="@color/black_my"
      app:layout_textsizepercent="12%"
      android:gravity="center"
      android:maxlines="1"
      android:ellipsize="end"/>
  </com.zhy.android.percent.support.percentlinearlayout>

layout_type代码:

<com.zhy.android.percent.support.percentlinearlayout
    android:id="@+id/layout_type"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:background="@color/white">
</com.zhy.android.percent.support.percentlinearlayout>

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

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网