st1989
st1989

Reputation: 1

change text on click of a button

I have created a small project where the text changes on the click of a button. However I am facing some issues:

My code of xml file is

<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Greetings appear here..."
        android:id="@+id/greetings_text_view"
        />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Show Greetings"
        android:layout_below="@id/greetings_text_view"
        android:onClick="showGreetings"/>

and my java code is

 TextView textview;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main); //connects java file with xml layout


        textview = (TextView).findViewById(R.id.greetings_text_view);
    }


    public void showGreetings ( View view) //creates method,  view is argument
    {
        String message="Welcome to first app";
        textview.setText(message);
    }

When I run the code I get this error:

Error:(20, 20) error: illegal start of type
Error:(20, 30) error: non-static method findViewById(int) cannot be referenced from a static context
Error:(20, 43) error: incompatible types: View cannot be converted to TextView

Can anyone please tell me where I went wrong?

Upvotes: 0

Views: 89

Answers (1)

pgiitu
pgiitu

Reputation: 1669

It is a minor problem (looks unintentional). When you do (TextView).findViewById(R.id.greetings_text_view) the compiler thinks that you are trying to call a static function findViewByIdof class TextView and that is why it is complaining

Replace

textview = (TextView).findViewById(R.id.greetings_text_view);

by this

textview = (TextView) findViewById(R.id.greetings_text_view);

Upvotes: 2

Related Questions