2016-03-04 136 views
0

我想要在Android中設置ImageView的寬度和高度。 不存在於XML中。在此創建:在DP Java中以編程方式設置ImageView大小

public void setImageView(int i,Integer d, LinearLayout layout) { 
    ImageView imageView = new ImageView(this); 
    imageView.setId(i); 
    imageView.setPadding(2, 2, 2, 2); 
    imageView.setImageBitmap(BitmapFactory.decodeResource(getResources(), d)); 
    imageView.setScaleType(ImageView.ScaleType.FIT_XY); 
    layout.addView(imageView); 
} 

它被放置到這個LinearLayout

<HorizontalScrollView 
    android:id="@+id/horizontal_scroll_view" 
    android:layout_width="fill_parent" 
    android:layout_gravity="center" 
    android:background="@drawable/white_lines" 
    android:layout_weight="15" 
    android:layout_height="0dp" > 

    <LinearLayout 
     android:id="@+id/scroll_view_layout" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:background="#999A9FA1" 
     android:orientation="horizontal" > 

    </LinearLayout> 

</HorizontalScrollView> 

所以基本上我稱之爲setImageView方法很多次,填補我HorizontalScrollViewImageViews封閉在LinearLayouts。我需要在DP中設置此高度而不是像素,以便它在所有設備中看起來都一樣!

回答

3

您需要將您的值轉換爲DPS,你可以使用下面的函數來進行:

public static int dpToPx(int dp, Context context) { 
    float density = context.getResources().getDisplayMetrics().density; 
    return Math.round((float) dp * density); 
} 
+0

好,做我怎麼設置'ImageView'大小有像素值。 – Alk

+0

執行此操作: LinearLayout.LayoutParams params =(LinearLayout.LayoutParams)imageView.getLayoutParams(); params.width = dpToPx(45); params.height = dpToPx(45); imageView.setLayoutParams(params); –

+0

更改LinearLayout您的ImageView所在的任何容器 –

相關問題