简体   繁体   English

如何在android的Java端设置文本样式?

[英]how to style text in Java side of android?

I have the below code, I want to make the timestamp to be smaller than the rest of the text but have been struggling for 2 days to get it to work. 我有下面的代码,我想使时间戳小于文本的其余部分,但是已经努力了2天才能使它起作用。

Code: 码:

private void alignTheMessageHistory(String username, String message, String sentdt) {

    StringBuffer sBuffer = new StringBuffer();
//  if (username.equals(friend.userName)) {
//      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.left_gray);
        valueTV.setPadding(15, 5, 10, 5);

    } else {
        params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        valueTV.setBackgroundResource(R.drawable.right_blue);
        valueTV.setPadding(10, 5, 15, 5);

    }

    params.setMargins(0, 5, 0, 0);
    sBuffer.append(((sentdt == null) 
            ? java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime()) 
            : sentdt)); ////////////////////////////NEED THIS TO BE SMALLER


    valueTV.setLayoutParams(params);
    valueTV.setText(sBuffer);
    //
    valueTV.post(new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            ((ScrollView) findViewById(R.id.scrollView))
                    .fullScroll(View.FOCUS_DOWN);
        }
    });
    layout.addView(valueTV);
    messageHistoryText.addView(layout);
}

You can use Spannable s or Html.fromHtml . 您可以使用SpannableHtml.fromHtml There are already some SO questions about this topic. 关于此主题已经有一些SO问题

Here is an example using the Html class: 这是使用Html类的示例:

String s = sentdt;
if(s == null) {
    s = java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());
}
valueTV.setText( Html.fromHtml(Html.escapeHtml(message) + "<br><small>" + s + "</small>") );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM