| 練習:輸入框+按鈕+文字顯示區 |
|
|
| Mobile / Android / 週一, 05 十月 2009 22:45 |
|
這是string.xml的內容 <?xml version="1.0" encoding="utf-8"?>在main.xml中的android:text="@string/btnText01"設定好後,就會自動對應 <button android:id="@+id/Button01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/btnText01"></button>最後,在Hello.java中,在建立專案時,就會產生以下的程式碼:
package com.eddychang.hello;
import android.app.Activity;
import android.os.Bundle;
public class Hello extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
在SetContentView(R.layout.main)後加上以下的程式碼:
Button btn = (Button) findViewById(R.id.Button01);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText edt = (EditText) Hello.this.findViewById(R.id.EditText01);
TextView txt = (TextView) Hello.this.findViewById(R.id.TextView01);
txt.setText(edt.getText());
}
});
這裡看到用這個findViewById可以找到在main.xml中設計好的widget,例如Button, EditText, TextView等等,用的都是"R.id.[WidgetID]"這個格式,要注意的是之前在main.xml的id都要用「@+id/Button01」的整串文字(有加上"@+id") 最後,這個程式碼還需要import相對的類別庫,在最上面的import程式碼,再加上以下的程式碼: import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; 評論: |

Joomla!台灣站長、資擘(股)軟體工程師