I am new to android studio and I have tried to write a simple program where the text "hello world" appears on the screen when a button is clicked, however, every time the button is clicked the program crashes.
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: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="com.example.numsm_000.helloworld.MainActivity">
<TextView
android:id="@+id/text"
android:layout_width="100dp"
android:layout_height="100dp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me!"
android:onClick="showMessage"
android:id="@+id/button"
android:layout_marginLeft="200dp"/>
</RelativeLayout>
MainActivity.java :
package com.example.numsm_000.helloworld;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void showMessage(){
TextView textView = (TextView) findViewById(R.id.text);
textView.setText(R.string.app_name);
}
}
Pass View
as a parameter to showMessage()
because onClick
will look for a method which has View
parameter
so it become
public void showMessage(View v){
TextView textView = (TextView) findViewById(R.id.text);
textView.setText(R.string.app_name);
}
Hope it helps :)
use following code
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
TextView textView;
Button btnClickMe;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.text);
btnClickMe=(Button)findViewById(R.id.button);
btnClickMe.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.button:
textView.setText(R.string.app_name);
break;
}
Try the following...
TextView textView = (TextView) findViewById(R.id.text);
Cut this line of code from showMessage() and put it in onCreate()... or you could just specify View view in ur method ..
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.