Android入门(2) 基本控件介绍、4种布局


一、基本控件介绍


一般新建组件有两种方式:XML中定义和Java代码实现,一般XML中定义较为常用。

1.Button


按钮,在main.xml中定义如下:

Button的监听器:onClickListener;

需要实现方法:public void onClick(View v); v表示触发的控件,比如按钮

代码示例:实现点击按钮生成随机数;


ButtonActivity.java

package org.xiazdong; import java.util.Random; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class ButtonActivity extends Activity implements OnClickListener{ //实现点击监听器 private Button button; private TextView tv; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); button = (Button)findViewById(R.id.button1); //根据ID找组件 tv = (TextView)findViewById(R.id.tv); button.setOnClickListener(this); //为button设置监听器 } @Override public void onClick(View view) { String str = new Random().nextInt()+""; tv.setText(str); Toast.makeText(this, "点击了按钮!!", Toast.LENGTH_SHORT).show(); //设置提示信息 Builder builder = new AlertDialog.Builder(this); //创建对话框 builder.setTitle("提示信息").setMessage("点击了按钮,随机数为:"+str).show(); //设置对话框属性并显示 } }


main.xml

2.ImageButton


和Button的区别为背景可以自定义图片,在main.xml中定义如下:


代码示例:实现点击图片按钮就切换图片;


main.xml

ImageButtonActivity.java

package org.xiazdong; import android.app.Activity; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.widget.ImageButton; public class ImageButtonActivity extends Activity { private ImageButton ib1; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ib1 = (ImageButton) findViewById(R.id.ib1); ib1.setOnTouchListener(new OnTouchListener(){ @Override public boolean onTouch(View v, MotionEvent event) { if(event.getAction()==MotionEvent.ACTION_DOWN){ //按下按钮时 ib1.setBackgroundResource(R.drawable.logo); } else if(event.getAction()==MotionEvent.ACTION_UP){ //抬起按钮时 ib1.setBackgroundResource(R.drawable.ic_launcher); } return false; } }); } }

3.EditText


文本框,在main.xml中定义如下:


可以在中设置以下属性:
(1)android:inputType="number":输入类型为数字;

(2)android:maxLength="2":输入最长为2;

(3)android:singleLine="true":只能单行显示;

(4)android:password="true" :输入的形式为密码

(5)android:numeric="integer":输入整数

代码示例:实现用户登录;


main.xml




    

        

        
    

    
 
        

        
    
 
    
   

EditTextActivity.java

package org.xiazdong;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class EditTextActivity extends Activity {
	private EditText name;
	private EditText password;
	private Button button;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		name = (EditText) findViewById(R.id.name);
		button = (Button) findViewById(R.id.button);
		password = (EditText) findViewById(R.id.password);
		button.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String n = name.getText().toString();
				String p = password.getText().toString();
				Builder builder = new AlertDialog.Builder(EditTextActivity.this); // 创建对话框
				builder.setTitle("提示信息").setMessage("用户名:" + n + "\n密码:" + p)
						.setPositiveButton("知道了", new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								password.setText("");	//清空密码
							}
						}).show(); 						// 设置对话框属性并显示
			}
		});
	}
}
 
    
   
 
   
 
   
 
   
 
   
 
   
 
   
 
   
 
  

4.CheckBox


多选框,在main.xml中定义如下:


onCheckedChangeListener监听器是专门对CheckBox进行监听,实现方法:public void onCheckedChanged(CompundButton buttonView,boolean isChecked);

代码示例:实现上海、北京、天津的复选框

main.xml




    

    

    

    

 
    
   
 
   
 
   
 
   
 
  

CheckBoxActivity.java

package org.xiazdong;

import android.app.Activity;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Toast;

public class CheckBoxActivity extends Activity implements
		OnCheckedChangeListener {
	private CheckBox cb1, cb2, cb3;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		cb1 = (CheckBox) findViewById(R.id.shanghai);
		cb2 = (CheckBox) findViewById(R.id.beijing);
		cb3 = (CheckBox) findViewById(R.id.tianjing);
		cb1.setOnCheckedChangeListener(this);
		cb2.setOnCheckedChangeListener(this);
		cb3.setOnCheckedChangeListener(this);
	}

	@Override
		public void onCheckedChanged(CompoundButton buttonView,   //buttonView表示改变的框,isChecked表示是选中还是取消选中
				boolean isChecked) {
			if(buttonView==cb1||buttonView==cb2||buttonView==cb3){
				if(isChecked){
					Toast.makeText(this, buttonView.getText()+"被选中",Toast.LENGTH_SHORT).show();
				}
				else{
					Toast.makeText(this, buttonView.getText()+"取消选中",Toast.LENGTH_SHORT).show();
				}
			}
		
		
	}
}
 
   
 
   
 
   
 
   
 
  

5.RadioButton


单选框,在main.xml中定义如下:

......
在单选框中也存在一个OnCheckedChangeListener,但是不同于多选框的监听器,虽然名字一样,但是所在包不一样。

代码示例:实现“男、女”单选框;

main.xml




    

        
        

        
        
    

 
    
   
 
   
 
   
 
   
 
  

RadioButtonActivity.java

package org.xiazdong;

import android.app.Activity;
import android.os.Bundle;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import android.widget.RadioGroup.OnCheckedChangeListener;

public class RadioButtonActivity extends Activity implements OnCheckedChangeListener{
    /** Called when the activity is first created. */
	private RadioButton rb1,rb2;
	private RadioGroup rg;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        rb1 = (RadioButton)findViewById(R.id.rb1);
        rb2 = (RadioButton)findViewById(R.id.rb2);
        rg = (RadioGroup)findViewById(R.id.rg1);
        rg.setOnCheckedChangeListener(this);
    }
	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {
		if(group==rg){
			if(rb1.getId()==checkedId){
				Toast.makeText(this, rb1.getText(), Toast.LENGTH_SHORT).show();
			}
			if(rb2.getId()==checkedId){
				Toast.makeText(this, rb2.getText(), Toast.LENGTH_SHORT).show();
			}
		}
	}
}
 
    
   
 
   
 
   
 
   
 
  


6.ProgressBar


进度条,在main.xml中定义如下:

android:layout_width="wrap_content" android:layout_height="wrap_content" />
1. ?andtroid:attr/progressBarStyleSmall圆形小进度条,动态
2. 默认,即不设置 圆形中等进度条,动态
3. ?android:attr/progressBarStyleLarge 圆形大进度条,动态
4. ?android:attr/progressBarStyleHorizontal 条状进度条,静态

条状进度条属性:


android:max
android:progress
android:secondaryProgress

代码示例:实现条状进度条,并当安装结束时,跳出提示


main.xml



    
 
    
   

ProgressBarActivity.java

package org.xiazdong;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.ProgressBar;
import android.widget.Toast;

public class ProgressBarActivity extends Activity implements Runnable {
	private ProgressBar bar;
	private boolean isFinished;
	Thread t;
	Handler handler = new Handler();
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		bar = (ProgressBar) findViewById(R.id.pb4);
		t = new Thread(this);
		t.start();
	}
	public void showToast() {
		handler.post(new Runnable() {
			@Override
			public void run() {
				Toast.makeText(getApplicationContext(), "安装完成!",		//此处需要使用Handler,因为不能在子线程中使用Toast
						Toast.LENGTH_SHORT).show();
			}
		});
	}
	public void run() {
		int current = bar.getProgress();
		int currentMax = bar.getMax();
		int secCurrent = bar.getSecondaryProgress();
		while (true) {
			bar.setProgress(current++);
			bar.setSecondaryProgress(secCurrent++);
			if (secCurrent >= currentMax) {
				break;
			}
			try {
				Thread.sleep(50);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		isFinished = true;
		showToast();
	}
}
 
   

7.TextView

文本显示组件,在main.xml中定义如下:
 
   
 
   
 
   
 
   
 
   
 
   
 
   
 
  



8.Dialog


对话框,不需要再main.xml中显示,只需要直接在Activity中创建即可;

(1)简单的Dialog:

常用函数:
setMessage()
setTitle()
setIcon()
setPositiveButton()
setNegativeButton()

Builder builder = new Builder(DialogActivity.this); //创建对话框 builder.setIcon(android.R.drawable.ic_dialog_info).setTitle("对话框标题"); //设置对话框图标和标题 builder.setMessage("对话框内容"); //设置对话框信息 builder.setPositiveButton("Yes", new OnClickListener(){ //设置正确按钮 @Override public void onClick(DialogInterface dialog, int arg1) { } }); builder.setNegativeButton("No", new OnClickListener(){ //设置否定按钮 @Override public void onClick(DialogInterface dialog, int arg1) { } }); builder.show(); //显示对话框

(2)在dialog中添加单选框和复选框:

实例:添加“上海、北京、天津”的多选框

setMultiChoiceItems();
setSingleChoiceItems();
注:设置这些和setMessage不能同时使用!

package org.xiazdong;

import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnMultiChoiceClickListener;
import android.os.Bundle;

public class DialogActivity extends Activity {
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Builder builder = new Builder(DialogActivity.this);
		builder.setMultiChoiceItems(new String[] { "上海", "北京", "天津" },   //每项内容
				new boolean[] { true, false, true },    //每项是否没选中
				new OnMultiChoiceClickListener() {    //监听器
					@Override
					public void onClick(DialogInterface dialog, int which,
							boolean isChecked) {
						
					}
				}).show();
	}
}
 
   
(3)在dialog中添加列表
builder.setItems(new String[]{"项1","项2"},new OnClickListener(){});
(4)在dialog中添加视图(在main.xml中定义):
setView函数实现; Builder builder = new Builder(DialogActivity.this); View layout = LayoutInflater.from(this).inflate(R.layout.main, null); builder.setIcon(android.R.drawable.ic_dialog_info).setTitle("对话框标题"); builder.setMessage("对话框内容"); builder.setPositiveButton("Yes", new OnClickListener(){ @Override public void onClick(DialogInterface dialog, int arg1) { } }); builder.setNegativeButton("Yes", new OnClickListener(){ @Override public void onClick(DialogInterface dialog, int arg1) { } }); builder.setView(layout); builder.show();
 
   
 
   
 
   
 
  

9.TabHost


分页组件,类似于如下图:



在main.xml中无需定义,直接在TabActivity中创建即可,但是TabSpec中的具体内容需要自定义,即引用布局文件中的ID;
注:
(1)Activity需要继承TabActivity 而不是Activity;
(2)OnTabChangedListener为TabHost的监听器,存在方法:public void onTagChanged(String tabId);

(3)TabSpec t1 = tabHost.newTabSpec("TabID");
(4)t1.setContent(布局或控件id); //为tabSpec添加某个布局
(5)t1.setIndicator(tab的标题);

代码示例:设置三页,每页有各自的内容

main.xml




    

        
    

    

        
    

    

        
    

 
   

TabHostActivity.java

package org.xiazdong;

import android.app.TabActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
import android.widget.Toast;

public class TabHostActivity extends TabActivity implements OnTabChangeListener {   //继承TabActivity而不是Activity
	TabHost host;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		host = this.getTabHost();    //新建TabHost
		LayoutInflater.from(this).inflate(R.layout.main,    //将main布局文件映射成tabHost的view
				host.getTabContentView());
		TabSpec t1 = host.newTabSpec("t1");   //新建一个页,id为t1
		t1.setIndicator("标签1");  //设置显示页名
		t1.setContent(R.id.l1);    //设置页的内容为l1布局,此处可以是布局或组件
		host.addTab(t1);     //加入TabHost中
		TabSpec t2 = host.newTabSpec("t2");
		t2.setIndicator("标签2",getResources().getDrawable(R.drawable.ic_launcher));
		t2.setContent(R.id.l2);
		host.addTab(t2);
		TabSpec t3 = host.newTabSpec("t3");
		t3.setIndicator("标签3");
		t3.setContent(R.id.l3);
		host.addTab(t3);
		host.setOnTabChangedListener(this);   //设置监听器
	}

	@Override
	public void onTabChanged(String tabId) {
		Log.v("a","aaaa");
		if(tabId.equals("t1")){
			Toast.makeText(this, "标签1ing", Toast.LENGTH_LONG).show();
		}
		if(tabId.equals("t2")){
			Toast.makeText(this, "标签2ing", Toast.LENGTH_LONG).show();
		}
		if(tabId.equals("t3")){
			Toast.makeText(this, "标签3ing", Toast.LENGTH_LONG).show();
		}
		else{
			Toast.makeText(this, tabId, Toast.LENGTH_LONG).show();
		}
	}
}
 
   
 
   
 
   
 
   
 
   
 
   
 
   
 
   
 
  

10.SeekBar


拖动条,在main.xml中定义如下:

注:存在OnSeekBarChangeListener监听器,用来监听SeekBar组件的事件,实现方法:
(1)public void onStartTrackingTouch(SeekBar seekBar); //开始移动时调用
(2)public void onStopTrackingTouch(SeekBar seekbar); //结束移动时调用
(3)public void onProgressChanged(SeekBar seekBar,int progress,boolean fromUser); //改变时调用,progress为当前值

代码示例:移动SeekBar组件,并在TextView中显示当前值

main.xml




    
	
 
   

SeekBarActivity.java

package org.xiazdong;

import android.app.Activity;
import android.os.Bundle;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

public class SeekBarActivity extends Activity {
	private TextView tv;
	private SeekBar sb;
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        tv = (TextView) findViewById(R.id.tv);
        sb = (SeekBar) findViewById(R.id.sb);
        sb.setOnSeekBarChangeListener(new OnSeekBarChangeListener(){
			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				tv.setText(progress+"");
			}
			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
			}
			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
			}
        });
    }
}
 
   

11.ListView

列表视图;

(1)使用ArrayAdapter实现普通列表

ArrayAdapter是一个媒介,通过它可以把数组映射到ListView视图上。
(1)new ArrayAapter(this,android.R.layout.simple_list_item_1,list); 将list存放到ArrayAdapter中;
(2)lv.setAdapter(adapter); 为listView设置Adapter;
package org.xiazdong; import java.util.ArrayList; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import android.widget.AdapterView.OnItemClickListener; public class ListViewActivity extends Activity implements OnItemClickListener{ ArrayList list; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); list = new ArrayList(); list.add("xiazdong-1"); list.add("xiazdong-2"); list.add("xiazdong-3"); ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,list); ListView lv = new ListView(this); lv.setAdapter(adapter); lv.setOnItemClickListener(this); this.setContentView(lv); } @Override public void onItemClick(AdapterView arg0, View arg1, int arg2, long arg3) { Toast.makeText(this,list.get(arg2), Toast.LENGTH_SHORT).show(); } }

(2)自定义适配器BaseAdapter



二、4种布局介绍


AbsoluteLayout因为已被废除,因此不做介绍;
只要存在界面,就会有布局的存在,就像Swing,虽然一个是桌面应用,一个是手机应用,但是他们都差不多。


此处因为布局非常简单,所以就不用代码来讲解了。


1.LinearLayout



默认布局。组件的排列按照预先定义方向很有序的排列,类似于Swing中的FlowLayout;
注意点:
 
   
 
   
 
   
 
   
 
   
 
   
 
   
 
  
(1)可以在中添加android:orientation:vertical/horizontal ;
(2)可以嵌套

2.FrameLayout


每个组件都在左上角,如果多个组件一起出现,则会重叠;

3.RelativeLayout


每个组件定位都是按照与其他组件的上下、左右定位;
默认的定位为左上方;
(1)定位与组件的上下左右
android:layout_below="@id/.."
android:layout_above="@id/"
android:layout_toLeftOf="@id/"
android:layout_toRightOf="@id/"
(2)定位与组件的边缘对齐
android:layout_alignLeft="@id/"
android:layout_alignRight="@id/"
android:layout_alignTop="@id/"
android:layout_alignBottom="@id/"
(3)定位与父组件的边缘对齐
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
(4)与整个屏幕的关系
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_centerInParent="true"

4.TableLayout


类似于Swing中的GridLayout;
表格布局的每行用括起来;
中可以定义如下属性:

(1)android:shrinkColumns="1" 表明第2个控件如果里面的内容过多,会收缩,扩展到第二行,而不是延伸;
(2)android:stretchColumns="2" 如果有空白,第3个控件填充;

在控件中设置:

(1)android:layout_column="2" 将此控件放在第3个位置;
(2)android:layout_span="2" 此控件占据2个单元位置;

补充:


1.在Activity中根据id获得strings.xml和main.xml中的内容


getResources().getString(int id);
getResources().getDrawable(int id);


2.锁定横竖屏


因为在CTRL+F11时 会发生问题,因此可以再AndroidManifest.xml的Activity设置:android:screenOrientation=""

(1)portrait:竖屏;
(2)landscape:横屏;

3.可视化设置布局、控件

main.xml 如下所示:


多个Activity之间跳转


使用Intent进行多个页面的跳转;
(1)Intent intent = new Intent(Context c,Class class); c表示当前界面,class表示要跳转到的界面的class;
(2)intent.putExtra(String key,String value); //设置传输内容;
(3)this.startActivity(intent); //开始跳转
(4)Intent intent = this.getIntent(); //获得传输来的intent
(5)String value = intent.getStringExtra(String key); //获得数据

代码示例:


main.xml

package org.xiazdong; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class MultiActivityActivity extends Activity implements OnClickListener{ private Button b1; private EditText e1; private TextView tv1; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); b1 = (Button)findViewById(R.id.b1); e1 = (EditText)findViewById(R.id.e1); tv1 = (TextView)findViewById(R.id.tv1); Intent i = this.getIntent(); if(i.getStringExtra("2")!=null){ tv1.setText(i.getStringExtra("2")); } b1.setOnClickListener(this); } @Override public void onClick(View v) { Intent intent = new Intent(MultiActivityActivity.this,OtherActivity.class); intent.putExtra("1", e1.getText().toString()); this.startActivity(intent); } }

OtherActivity.java

package org.xiazdong; import android.app.Activity; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class OtherActivity extends Activity implements OnClickListener{ private TextView view ; private Button b2; private EditText e2; private TextView tv2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); view = new TextView(this); setContentView(R.layout.mylayout); b2 = (Button)findViewById(R.id.b2); e2 = (EditText)findViewById(R.id.e2); tv2 = (TextView)findViewById(R.id.tv2); Intent i = this.getIntent(); if(i.getStringExtra("1")!=null){ tv2.setText(i.getStringExtra("1")); } b2.setOnClickListener(this); } @Override public void onClick(View v) { Intent intent = new Intent(OtherActivity.this,MultiActivityActivity.class); intent.putExtra("2", e2.getText().toString()); this.startActivity(intent); } }


 
  
 
  
 
  
 
  
 
  
 
 

你可能感兴趣的:(移动开发,java)