Android动态添加view的方法示例

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

这里的按钮数量是可变的.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。

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

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。