首页 > 系统 > Android > 正文

Android动态添加view的方法示例

2019-10-22 18:25:25
字体:
来源:转载
供稿:网友

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

Android动态添加view,动态添加webview

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

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


注:相关教程知识阅读请移步到Android开发频道。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表