[Android] How to change text in TextView programmatically

Collapse
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • [Android] How to change text in TextView programmatically

    Greetings one and all,

    If you are thinking about venturing off into Mobile App development then kudos to you. Below I will demonstrate how you can change a textView text programmatically and I will create a next topic demonstrating how you can animate a TextView.

    I am assuming that you already have Eclipse or Android Studio etc installed. In my case I am using Android Studio.

    First you create a project, (give it whatever name you want etc) then add a TextView with some text to the default activity_main.xml

    Then find your view:

    Code:
       TextView myTextView = (TextView) findViewById(R.id.TextView1);
    Then you can change the default text for you TextView like so:

    Code:
       myTextView.seText("Hello Coding-Talk.com");
    Complete Code below:

    Java:
    Code:
    package andre3.com.playrounds;
    
    import android.R;
    import android.app.Activity;
    import android.os.Bundle;
    import android.widget.TextView;
    
    public class MainActivity extends Activity {
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    
    TextView myTextView = (TextView)findViewById(R.id.TextView1);
    myTextView.setText("Hello Coding-Talk.com");
    
    }
    
    }
    XML:
    Code:
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="andre3.com.playrounds.MainActivity" >
    
    <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/TextView1"
    android:text="@string/hello_world" />
    
    </RelativeLayout>
    Last edited by andre3; 11.07.16, 12:57.
Working...
X