Sunday, August 19, 2012

Android - TextView Example

In Android, There are UI components which are used to develop more interactive interface. To develop user friendly interface we need to explore each component.

Below is example for Textview, it can be used to display static text in the application. It is having more features and through which we can develop interface like text editor.

I used Eclipse as development tool and tested the sample in Emulator for Android 4.0.3.

There are lot of resources are used to develop android app. but for this example, we are using three basis components like code base file, layout file and string file.

Below is code of Layout file.


<LinearLayout 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:orientation="vertical" >

    <TextView
android:id="@+id/tvtitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/tvtitle"
        tools:context=".TextViewExample" />

    <Button
        android:id="@+id/btnok"
        android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/btnok"
/>
</LinearLayout>

Code of Strings.xml file:


<resources>

    <string name="app_name">TextViewExample</string>
    <string name="tvtitle"></string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_text_view_example">Text View Example</string>
    <string name="btnok">Click Me</string>

</resources>


Code of Java file (Source):


package com.example.textviewexample;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class TextViewExample extends Activity {

Button btnOk;
TextView tvTitle;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_text_view_example);
        
        btnOk = (Button) findViewById(R.id.btnok);
        tvTitle = (TextView) findViewById(R.id.tvtitle);
        
        onButtonClickListener();
        
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_text_view_example, menu);
        return true;
    }
    
    public void onButtonClickListener(){
    btnOk.setOnClickListener(new OnClickListener() {

public void onClick(View arg0) {
// TODO Auto-generated method stub
tvTitle.setText("Hi Friends!!!");
}
});
    }
}



Note: click on button and it will show you "Hi Friends!!!" text in textview.





No comments:

Post a Comment