主界面代碼 主活動代碼: ...
主界面代碼
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <Button android:id="@+id/change" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="改變內容"/> <TextView android:id="@+id/text" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="你好,世界!" android:textSize="20sp"/> </RelativeLayout>
主活動代碼:
import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class MainActivity extends AppCompatActivity implements View.OnClickListener{ private TextView text; public static final int UPDATE_TEXT=1; private Handler handler=new Handler(){ public void handleMessage(Message msg){ switch (msg.what){ case UPDATE_TEXT: text.setText("遇見你真好"); break; default: break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); text=(TextView)findViewById(R.id.text); Button ChangeText=(Button)findViewById(R.id.change); ChangeText.setOnClickListener(this); } public void onClick(View v) { switch (v.getId()) { case R.id.change: new Thread(new Runnable() { @Override public void run() { Message message=new Message(); message.what=UPDATE_TEXT; handler.sendMessage(message); } }).start(); break; default: break; } } }