android代码中动态设置布局中控件的属性

1、获取屏幕长宽像素及通过id查找各布局或控件:

        DisplayMetrics metric = new DisplayMetrics();   
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        mScreenWidth = metric.widthPixels;  // 屏幕宽度(像素)   
        mScreenHeight = metric.heightPixels;  // 屏幕高度(像素)   
        float density = metric.density;  // 屏幕密度(0.75 / 1.0 / 1.5)   
        int densityDpi = metric.densityDpi;
        mDipWidth = (int)(mScreenWidth/density);//设备独立宽像素
        mDipHeight = (int)(mScreenHeight/density);//设备独立高像素
        mAudio_title_Linear = (LinearLayout) findViewById(R.id.audio_title_Linear);
        mAudio_info_Linear = (LinearLayout) findViewById(R.id.audio_info_Linear);

        mAlbum = (ImageView) findViewById(R.id.album);

        mAudio_title_txt = (TextView) findViewById(R.id.audio_title_txt);

 

       2、向获得的布局中设置宽高及内间距
        mAudio_title_Linear.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,mScreenHeight/6));
        mAudio_info_Linear.setPadding(mScreenHeight/10, mScreenHeight/20, 0, 0);
        mAudio_info_Linear.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,mScreenHeight*7/10));
        mAudio_info_Linear.setPadding(0, mScreenHeight/48, 0, mScreenHeight/48);

 

       3、为控件(ImageView和TextView)设置宽高和外间距
        LayoutParams params = mAlbum.getLayoutParams();
        params.width = mScreenWidth*34/100;
        params.height = mScreenHeight*58/100;
        //mAlbum.setLayoutParams(params);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(params.width, params.height); 
        lp.setMargins(mScreenHeight*2/100, mScreenHeight*3/100, mScreenHeight*3/100, 0);       
        mAlbum.setLayoutParams(lp);
        mAudio_title_txt.setTextSize(mScreenHeight*4/100);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值