Android动态添加view设置view大小(宽高)

简介: Android动态添加view设置view大小(宽高)

动态生成view并添加到布局开源框架:Dynamico

GitHub - jelic98/dynamico: Android library for inflating dynamic layouts in runtime based on JSON configuration fetched from server

第一种:ViewGroup在添加子view的时候设置layoutParams

public static View generalView(Activity context) {
        NestedScrollView scrollView = new NestedScrollView(context);
        //ScrollView加上android:fillViewport=“true”,当子view小于ScrollView高度时就会占满父View
        scrollView.setFillViewport(true);
 
        FrameLayout frameLayout = new FrameLayout(context);
        //控制视图背景
        frameLayout.setBackgroundColor(context.getResources().getColor(android.R.color.background_dark, null));
 
        GuiTextView titleTextView = new GuiTextView(context);
        titleTextView.setText(title);
 
        GuiTextView contentView = new GuiTextView(context);
        contentView.setText(text);
        //contentView.setMaxEms(30);
 
        GuiImageView imageView = new GuiImageView(context);
        imageView.setImageDrawable(context.getDrawable(R.mipmap.ic_car));
 
 
 
        //RecyclerView
        GuiRecyclerView recyclerView = new GuiRecyclerView(context);
        GuiListAdapter listAdapter = new GuiListAdapter();
        recyclerView.setAdapter(listAdapter);
 
 
        // 将控件加入到当前布局中
        frameLayout.addView(titleTextView, ViewUtils.getLayoutParam(context,100, 20, 100, 10));
        frameLayout.addView(contentView, ViewUtils.getLayoutParam(context,220, 120, 20, 50));
        frameLayout.addView(imageView, ViewUtils.getLayoutParam(context,220, 124, 20, 180));
        frameLayout.addView(recyclerView, ViewUtils.getLayoutParam(context,220, 120, 20, 320));
 
        ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        scrollView.addView(frameLayout);
 
        return scrollView;
 
    }

第二种:子view本身设置layoutParams

 public static View generalMediaView(Activity context) {
        NestedScrollView scrollView = new NestedScrollView(context);
        //ScrollView加上android:fillViewport=“true”,当子view小于ScrollView高度时就会占满父View
        scrollView.setFillViewport(true);
 
        FrameLayout frameLayout = new FrameLayout(context);
        //控制视图背景
        frameLayout.setBackgroundColor(context.getResources().getColor(android.R.color.background_dark, null));
 
        GuiTextView titleTextView = new GuiTextView(context);
        titleTextView.setText(title);
        titleTextView.setBackgroundColor(context.getResources().getColor(android.R.color.holo_orange_light, null));
        FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(DisplayUtil.dip2px(context, 200), DisplayUtil.dip2px(context, 40));
        layoutParams.setMargins(DisplayUtil.dip2px(context, 50), DisplayUtil.dip2px(context, 100), 0, 0);
        titleTextView.setLayoutParams(layoutParams);
 
 
 
        // 将控件加入到当前布局中
        frameLayout.addView(titleTextView);
 
        scrollView.addView(frameLayout);
 
        return scrollView;
 
    }

DisplayUtil.java

public class DisplayUtil {
 
    public static int getScreenWidthByPix(Context context) {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        return dm.widthPixels;
    }
 
    public static int getScreenWidthByDp(Context context) {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        return (int) (dm.widthPixels / dm.density);
    }
 
    public static int getScreenHeightByPix(Context context) {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        return dm.heightPixels;
    }
 
    public static int getRealHeightByPix(Context context) {
        WindowManager mWindowManager = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        if (mWindowManager == null) {
            return getScreenHeightByPix(context);
        }
        Display mDisplay = mWindowManager.getDefaultDisplay();
        DisplayMetrics mDisplayMetrics = new DisplayMetrics();
        mDisplay.getRealMetrics(mDisplayMetrics);
        return mDisplayMetrics.heightPixels;
    }
 
    public static int getScreenHeightByDp(Context context) {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        return (int) (dm.heightPixels / dm.density);
    }
 
    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
 
    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        return px2dip(context, pxValue, true);
    }
 
    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     * isUp 向上取整
     */
    public static int px2dip(Context context, float pxValue, boolean isUp) {
        final float scale = context.getResources().getDisplayMetrics().density;
        if (isUp) {
            return (int) (pxValue / scale + 0.5f);
        } else {
            return (int) (pxValue / scale);
        }
    }
 
 
    /**
     * 设置某个View的margin
     *
     * @param view   需要设置的view
     * @param isDp   需要设置的数值是否为DP
     * @param left   左边距
     * @param right  右边距
     * @param top    上边距
     * @param bottom 下边距
     * @return
     */
    public static ViewGroup.LayoutParams setViewMargin(View view, boolean isDp, int left, int right, int top, int bottom) {
        if (view == null) {
            return null;
        }
 
        int leftPx = left;
        int rightPx = right;
        int topPx = top;
        int bottomPx = bottom;
        ViewGroup.LayoutParams params = view.getLayoutParams();
        ViewGroup.MarginLayoutParams marginParams = null;
        //获取view的margin设置参数
        if (params instanceof ViewGroup.MarginLayoutParams) {
            marginParams = (ViewGroup.MarginLayoutParams) params;
        } else {
            //不存在时创建一个新的参数
            marginParams = new ViewGroup.MarginLayoutParams(params);
        }
 
        //根据DP与PX转换计算值
        if (isDp) {
            leftPx = px2dip(view.getContext(), left);
            rightPx = px2dip(view.getContext(), right);
            topPx = px2dip(view.getContext(), top);
            bottomPx = px2dip(view.getContext(), bottom);
        }
        //设置margin
        marginParams.setMargins(leftPx, topPx, rightPx, bottomPx);
        view.setLayoutParams(marginParams);
        return marginParams;
    }
 
 
    @SuppressWarnings("deprecation")
    /**
     * 兼容4.0与4.1以上系统设置BackgroundDrawable方法不同
     */
    public static void setBackgroundDrawableCompat(View view, Drawable drawable) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
            view.setBackgroundDrawable(drawable);
        } else {
            view.setBackground(drawable);
        }
    }
 
    /**
     * 获取屏幕分辨率
     *
     * @param context
     * @return
     */
    public static String getStrScreenResolution(Application context) {
 
        DisplayMetrics dm = new DisplayMetrics();
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        windowManager.getDefaultDisplay().getMetrics(dm);//display = getWindowManager().getDefaultDisplay();display.getMetrics(dm)(把屏幕尺寸信息赋值给DisplayMetrics dm);
        int width = dm.widthPixels;
        int height = dm.heightPixels;
 
        return width + "*" + height;
    }
 
    /**
     * 获取 是否是平板设备
     *
     * @param context
     * @return true:平板,false:手机
     */
    public static boolean isTabletDevice(Context context) {
        return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >=
                Configuration.SCREENLAYOUT_SIZE_LARGE;
    }
 
 
    /**
     * 修改屏幕当前亮度
     *
     * @param context
     * @param brightness
     */
    public static void setScreenBritness(Activity context, int brightness) {
        WindowManager.LayoutParams lp = context.getWindow().getAttributes();
        lp.screenBrightness = Float.valueOf(brightness) * (1f / 255f);
        context.getWindow().setAttributes(lp);
    }
 
    /**
     * 获取系统亮度
     *
     * @return
     */
    public static int getSystemBrightness(Activity context) {
        int systemBrightness = 0;
        try {
            systemBrightness = Settings.System.getInt(context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
        } catch (Settings.SettingNotFoundException e) {
            e.printStackTrace();
        }
        return systemBrightness;
    }
 
    /**
     * 检测是否开启了自动亮度调整
     *
     * @param activity
     * @return
     */
    public static boolean isAutoBrightness(Activity activity) {
        try {
            int autoBrightness = Settings.System.getInt(
                    activity.getContentResolver(),
                    Settings.System.SCREEN_BRIGHTNESS_MODE);
            if (autoBrightness == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) {
                return true;
            }
        } catch (Settings.SettingNotFoundException e) {
            e.printStackTrace();
        }
        return false;
    }
 
    /**
     * 关闭系统自动调节亮度
     *
     * @param activity
     */
    public static void closeAutoBrightness(Activity activity) {
        Settings.System.putInt(activity.getContentResolver(),
                Settings.System.SCREEN_BRIGHTNESS_MODE,
                Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
    }
 
    /**
     * 打开自动调节亮度
     *
     * @param activity
     */
    public static void openAutoBrightness(Activity activity) {
        setScreenBritness(activity, -1);
        Settings.System.putInt(activity.getContentResolver(),
                Settings.System.SCREEN_BRIGHTNESS_MODE,
                Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
    }
 
    /**
     * 获取屏幕密度
     */
    public static int getPixelRation(Context context) {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        return dm.densityDpi;
    }
 
}

ViewUtils.java

public class ViewUtils {
 
    public static FrameLayout.LayoutParams getLayoutParam(Context context, int width, int height, int startX, int startY) {
        int w = DisplayUtil.dip2px(context, width);
        int h = DisplayUtil.dip2px(context, height);
        int x = DisplayUtil.dip2px(context, startX);
        int y = DisplayUtil.dip2px(context, startY);
 
        FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(w, h);
        layoutParams.setMargins(x, y, 0, 0);
        return layoutParams;
    }
}


相关文章
|
7月前
|
Android开发 UED 计算机视觉
Android自定义view之线条等待动画(灵感来源:金铲铲之战)
本文介绍了一款受游戏“金铲铲之战”启发的Android自定义View——线条等待动画的实现过程。通过将布局分为10份,利用`onSizeChanged`测量最小长度,并借助画笔绘制动态线条,实现渐变伸缩效果。动画逻辑通过四个变量控制线条的增长与回退,最终形成流畅的等待动画。代码中详细展示了画笔初始化、线条绘制及动画更新的核心步骤,并提供完整源码供参考。此动画适用于加载场景,提升用户体验。
537 5
Android自定义view之线条等待动画(灵感来源:金铲铲之战)
|
7月前
|
Android开发
Android自定义view之利用PathEffect实现动态效果
本文介绍如何在Android自定义View中利用`PathEffect`实现动态效果。通过改变偏移量,结合`PathEffect`的子类(如`CornerPathEffect`、`DashPathEffect`、`PathDashPathEffect`等)实现路径绘制的动态变化。文章详细解析了各子类的功能与参数,并通过案例代码展示了如何使用`ComposePathEffect`组合效果,以及通过修改偏移量实现动画。最终效果为一个菱形图案沿路径运动,源码附于文末供参考。
131 0
|
7月前
|
Android开发 开发者
Android自定义view之利用drawArc方法实现动态效果
本文介绍了如何通过Android自定义View实现动态效果,重点使用`drawArc`方法完成圆弧动画。首先通过`onSizeChanged`进行测量,初始化画笔属性,设置圆弧相关参数。核心思路是不断改变圆弧扫过角度`sweepAngle`,并调用`invalidate()`刷新View以实现动态旋转效果。最后附上完整代码与效果图,帮助开发者快速理解并实践这一动画实现方式。
187 0
|
7月前
|
Android开发 数据安全/隐私保护 开发者
Android自定义view之模仿登录界面文本输入框(华为云APP)
本文介绍了一款自定义输入框的实现,包含静态效果、hint值浮动动画及功能扩展。通过组合多个控件完成界面布局,使用TranslateAnimation与AlphaAnimation实现hint文字上下浮动效果,支持密码加密解密显示、去除键盘回车空格输入、光标定位等功能。代码基于Android平台,提供完整源码与attrs配置,方便复用与定制。希望对开发者有所帮助。
133 0
|
7月前
|
XML Java Android开发
Android自定义view之网易云推荐歌单界面
本文详细介绍了如何通过自定义View实现网易云音乐推荐歌单界面的效果。首先,作者自定义了一个圆角图片控件`MellowImageView`,用于绘制圆角矩形图片。接着,通过将布局放入`HorizontalScrollView`中,实现了左右滑动功能,并使用`ViewFlipper`添加图片切换动画效果。文章提供了完整的代码示例,包括XML布局、动画文件和Java代码,最终展示了实现效果。此教程适合想了解自定义View和动画效果的开发者。
343 65
Android自定义view之网易云推荐歌单界面
|
7月前
|
XML 前端开发 Android开发
一篇文章带你走近Android自定义view
这是一篇关于Android自定义View的全面教程,涵盖从基础到进阶的知识点。文章首先讲解了自定义View的必要性及简单实现(如通过三个构造函数解决焦点问题),接着深入探讨Canvas绘图、自定义属性设置、动画实现等内容。还提供了具体案例,如跑马灯、折线图、太极图等。此外,文章详细解析了View绘制流程(measure、layout、draw)和事件分发机制。最后延伸至SurfaceView、GLSurfaceView、SVG动画等高级主题,并附带GitHub案例供实践。适合希望深入理解Android自定义View的开发者学习参考。
690 84
|
7月前
|
前端开发 Android开发 UED
讲讲Android为自定义view提供的SurfaceView
本文详细介绍了Android中自定义View时使用SurfaceView的必要性和实现方式。首先分析了在复杂绘制逻辑和高频界面更新场景下,传统View可能引发卡顿的问题,进而引出SurfaceView作为解决方案。文章通过Android官方Demo展示了SurfaceView的基本用法,包括实现`SurfaceHolder.Callback2`接口、与Activity生命周期绑定、子线程中使用`lockCanvas()`和`unlockCanvasAndPost()`方法完成绘图操作。
208 3
|
7月前
|
Android开发 开发者
Android自定义view之围棋动画(化繁为简)
本文介绍了Android自定义View的动画实现,通过两个案例拓展动态效果。第一个案例基于`drawArc`方法实现单次动画,借助布尔值控制动画流程。第二个案例以围棋动画为例,从简单的小球直线运动到双向变速运动,最终实现循环动画效果。代码结构清晰,逻辑简明,展示了如何化繁为简实现复杂动画,帮助读者拓展动态效果设计思路。文末提供完整源码,适合初学者和进阶开发者学习参考。
141 0
Android自定义view之围棋动画(化繁为简)
|
7月前
|
Java Android开发 开发者
Android自定义view之围棋动画
本文详细介绍了在Android中自定义View实现围棋动画的过程。从测量宽高、绘制棋盘背景,到创建固定棋子及动态棋子,最后通过属性动画实现棋子的移动效果。文章还讲解了如何通过自定义属性调整棋子和棋盘的颜色及动画时长,并优化视觉效果,如添加渐变色让白子更明显。最终效果既可作为围棋动画展示,也可用作加载等待动画。代码完整,适合进阶开发者学习参考。
155 0
|
7月前
|
传感器 Android开发 开发者
Android自定义view之3D正方体
本文介绍了如何通过手势滑动操作实现3D正方体的旋转效果,基于Android自定义View中的GLSurfaceView。相较于使用传感器控制,本文改用事件分发机制(onTouchEvent)处理用户手势输入,调整3D正方体的角度。代码中详细展示了TouchSurfaceView的实现,包括触控逻辑、OpenGL ES绘制3D正方体的核心过程,以及生命周期管理。适合对Android 3D图形开发感兴趣的开发者学习参考。
121 0

热门文章

最新文章