3

在布局文件中,我有以下内容:

    android:layout_width="100dp" 
    android:layout_height="wrap_content" android:layout_marginRight="10dp" 
    android:text="SYN" 
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:background="@drawable/rectanglepurple"
    android:textColor="#000000" 
    android:gravity="right"/>

我正在尝试使用代码实现以下目标,到目前为止我有:

Resources res = getResources();
Drawable drawable1=res.getDrawable(R.drawable.rectanglepurple);

TextView idText = new TextView(getActivity());
    idText.setText("SYN");
    idText.setTextAppearance(getActivity(), android.R.style.TextAppearance_Medium);
    idText.setTextColor(Color.BLACK);
    idText.setGravity(Gravity.RIGHT);
    idText.setBackgroundDrawable(drawable1);

我不能锻炼如何处理

    android:layout_width="100dp" 
    android:layout_height="wrap_content" android:layout_marginRight="10dp" 

任何帮助表示赞赏。

4

2 回答 2

7

This is an interesting part of Android layouts. The XML properties that are prefixed with layout_ are actually for the containing view manager (like LinearLayout or RelativeLayout). So you need to add something like this:

//convert from pixels (accepted by LayoutParams) to dp
int px = convertDpToPixel(100, this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(px, LinearLayout.LayoutParams.WRAP_CONTENT);
//convert from pixels (taken by LayoutParams.rightMargin) to dp
px = convertDpToPixel(10, this);
params.rightMargin = px;
idText.setLayoutParams(params);

And the convertDpToPixel (shamelessly adapted (change to return int instead of float) from Converting pixels to dp ):

/**
* This method converts dp unit to equivalent device specific value in pixels.
*
* @param dp      A value in dp(Device independent pixels) unit. Which we need to convert into pixels
* @param context Context to get resources and device specific display metrics
* @return An integer value to represent Pixels equivalent to dp according to device
*/
public static int convertDpToPixel(float dp, Context context) {
    Resources resources = context.getResources();
    DisplayMetrics metrics = resources.getDisplayMetrics();
    int px = (int) (dp * (metrics.densityDpi / 160f));
    return px;
}

EDIT: changed the assignment to rightMargin from 10 (# of pixels) to the variable px (containing the number of pixels in 10dp) whoopsie.

于 2012-10-11T22:26:20.700 回答
0

你可能想看看

 setLayoutParams()

TextView 类的方法。--安卓文档

于 2012-10-11T22:22:40.603 回答