简体   繁体   中英

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.

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 . There are already some SO questions about this topic.

Here is an example using the Html class:

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>") );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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