Sunday, March 13, 2016

android - Display degree symbol in a TextView

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".MainActivity"
    android:background="#f1fbfc"
    >
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="40dp"
        android:layout_margin="10dp"
        android:padding="10dp"
        android:textStyle="bold"
        android:fontFamily="sans-serif-condensed"
        android:textColor="#227aed"
        android:text="Degree symbol in XML\nTemperature is 34.5\u00B0"
        />
    <TextView
        android:id="@+id/tv_second"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="40dp"
        android:layout_margin="10dp"
        android:padding="10dp"
        android:textStyle="bold"
        android:fontFamily="sans-serif-condensed"
        android:textColor="#ed22df"
        android:layout_below="@id/tv"
        />
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.app.Activity;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.RelativeLayout;
import android.widget.TextView;


public class MainActivity extends AppCompatActivity {

    private Context mContext;
    private Activity mActivity;

    private RelativeLayout mRelativeLayout;
    private TextView mTextView;
    private TextView mTextViewSecond;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Get the application context
        mContext = getApplicationContext();

        // Get the activity
        mActivity = MainActivity.this;

        // Get the widgets reference from XML layout
        mRelativeLayout = (RelativeLayout) findViewById(R.id.rl);
        mTextView = (TextView) findViewById(R.id.tv);
        mTextViewSecond = (TextView) findViewById(R.id.tv_second);

        // Display a degree symbol programmatically in a TextView
        mTextViewSecond.setText("Degree symbol in code : " + "45.7" + (char) 0x00B0);
    }
}