安卓:编程设置ImageView的layout_height [英] Android: Set ImageView layout_height programmatically

查看:197
本文介绍了安卓:编程设置ImageView的layout_height的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的main.xml文件中的ImageView的:

I have an ImageView in my main.xml file:

<ImageView
            android:id="@+id/pageImage"
            android:layout_width="270dp"
            android:layout_height="45dp"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_marginLeft="25dp"
            android:layout_marginTop="15dp"
            android:scaleType="fitXY"
            android:src="@drawable/pageimage" />

我只需要做的是设置了 layout_height 编程为其他值。

此外,我需要设置的值 DP 。因此,它是目前45dp,我想将其更改为另一个值在我的主要活动。

Additionally, I need to set the value in dp. So it is currently 45dp, I'd like to change it to another value in my main activity.

我试图找出如何使用的LayoutParams做到这一点,但我不能成功。

I tried to figure out how to do this using LayoutParams, but I couldn't succeed.

感谢。

推荐答案

我想你想是这样的:

ImageView imgView = (ImageView) findViewById(R.id.pageImage);
imgView.getLayoutParams().height = 200;

所以,首先我们从XML的ImageView的。然后getLayoutParams()让你正是你可以编辑然后PARAMS。您可以将它们直接在那里。同为宽度等。

So first we get the ImageView from the XML. Then getLayoutParams() gets you exactly the params you may edit then. You can set them directly there. The same for the width etc.

关于本机(SP,DP ...),我发现这里的东西。希望这有助于:

About the unit (sp,dp...) I found something here. Hope this helps:

使用DIP,SP指标编程

在那里,他们提到,所有的单位是像素。在这个例子中,他设置的最小宽度20SP像这样的的:

There they mention, that all units are pixels. In the example he sets the minimum width of 20sp like this:

TextView tv0 = new TextView(this);
int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 20, getResources().getDisplayMetrics());
tv0.setMinimumWidth(px);

P.S。下面是完整的code我用。希望这是你想要的:

P.S. Here is the complete code I use. Hopefully this is what you want:

package com.example.testproject2;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ImageView;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ImageView imgView = (ImageView) findViewById(R.id.pageImage);
        imgView.getLayoutParams().height = 500;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}

这篇关于安卓:编程设置ImageView的layout_height的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆