温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Android动态添加view的方法示例

发布时间:2020-08-25 07:04:39 来源:脚本之家 阅读:106 作者:楊帥 栏目:移动开发

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

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。

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

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI