Button

初次接触Android,这个东西还是挺有意思的。界面的格式布局使用Xml文件进行设置,而所使用的代码则与布局分离,代之以Java文件,就象是写Asp.net文件。奇怪的是在代码中使用控件名称时,却类似于JavaScript一类的寻找,试了一下,如下图:

代码
package com.test.android;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class HelloAndroid extends Activity {
    
/** Called when the activity is first created. */
    @Override
    
public void onCreate(Bundle savedInstanceState) {
        
super.onCreate(savedInstanceState);
        
//使用main的布局
        setContentView(R.layout.main);
        
//获得Button对象
        Button btn = (Button)findViewById(R.id.Button01);
        
//设置监听
        btn.setOnClickListener(new Button.OnClickListener(){
            
public void onClick(View v){
                dispToast(
"点击了按钮");
            }
        });
        
//获得TextView对象,此类如同.Net或Delphi中的Label
        TextView tv = (TextView)findViewById(R.id.TextView01);
        tv.setTextColor(Color.RED);
        tv.setTextSize(
20);
        tv.setBackgroundColor(Color.YELLOW);
        tv.setText(
"显示文本");
    }
    
public void dispToast(String str){
        Toast.makeText(
this, str, Toast.LENGTH_LONG).show();
    }
    
//显示触点的位置
    public boolean onTouchEvent(MotionEvent event){
        
int selectAction = event.getAction();
        
if (selectAction == MotionEvent.ACTION_CANCEL ||
            selectAction 
== MotionEvent.ACTION_DOWN ||
            selectAction 
== MotionEvent.ACTION_MOVE)
            
return false;
        
        
int x = (int)event.getX();
        
int y = (int)event.getY();
        
this.dispToast("触点坐标: x " + Integer.toString(x)+" y "+Integer.toString(y));
        
return super.onTouchEvent(event);
    }
}
原文地址:https://www.cnblogs.com/wjhx/p/1679439.html