0

我只想为代码内的文本设置边距,而不是背景资源。我将如何做这件事?

背景是 9patch 图像。

这是我的代码片段。

    StringBuffer sBuffer = new StringBuffer();
    sBuffer.append(sent + ":\n");
    sBuffer.append(username + ":\n");
    sBuffer.append(message + "\n");

    RelativeLayout layout = new RelativeLayout(this);
    RelativeLayout.LayoutParams topParams = new RelativeLayout.LayoutParams(
            android.view.ViewGroup.LayoutParams.MATCH_PARENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
    topParams.setMargins(10, 10, 10, 10);
    layout.setLayoutParams(topParams);

    TextView valueTV = new TextView(this);
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
            android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT);

    if (username.equals(friend.userName)) {
        params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
        valueTV.setBackgroundResource(R.drawable.chat_bub_left_blue);
        params.setMargins(20, 10, 10, 10);

    } else {
        params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        valueTV.setBackgroundResource(R.drawable.chat_bub_right_green);
        params.setMargins(60, 10, 10, 30);
    }

    valueTV.setLayoutParams(params);
    valueTV.setText(sBuffer);
4

2 回答 2

0

您需要将参数应用于文本视图。假设您想在代码中使用边距参数,您可以这样做。

valueTV.setLayoutParams(params);
于 2013-10-24T14:11:20.767 回答
0

你试过文字填充吗?就是这样:

http://developer.android.com/reference/android/view/View.html#setPadding%28int,%20int,%20int,%20int%29

于 2013-10-24T14:06:14.497 回答