android程式設計實例入門 -Sample改寫分享 (2014/09/05)
android程式設計實例入門 -Sample改寫分享 (2014/09/05)
此範例為程式碼(03\Sample4)的改寫,利用一個LinearLayout、一個TextView和一個Button元件實作GUI界面,並且利用SampleClickListener讓按鈕擁有事件反應能力,程式碼如下所示:
package com.jashsample;
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.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
public class MainActivity extends Activity {
public TextView tv;
public Button bt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
setContentView(ll);
tv = new TextView(this);
tv.setText("歡迎光臨。");
bt = new Button(this);
bt.setText("購買");
ll.addView(tv);
ll.addView(bt);
bt.setOnClickListener(new SampleClickListener()); //設定按鈕事件反應
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
class SampleClickListener implements OnClickListener//按鈕事件反應類別
{
public void onClick(View v)
{
tv.setText("謝謝惠顧。");
}
}
}