Android的学习3-初识Activity

时间:2014-05-03 17:29:15   收藏:0   阅读:410

Activity---android的系统下存放控件的容器。通俗的讲相当于MFC中的CFrame。搭配完成android4.4.2开发环境后,发现比2.1的开发效率高很多。

android的2.1是依靠xml添加和表述控件,但4.4.2提供了可视化的编辑工具,加快了开发速度。

bubuko.com,布布扣

我们添加一个按钮,并在MainActivty.java中添加按钮的命令响应。

1、如何获取控件呢?我们查阅Activity的帮助文件发现有findViewById函数。通过资源ID索引控件。

2、学过java的人都知道添加Listener内部类,实现button的内部响应

3、button设置监听。关联内部监听类。

具体代码如下

package com.example.myactivity;

import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.os.Build;

public class MainActivity extends ActionBarActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		Button myButton = (Button)findViewById(R.id.button1);
		
		myButton.setOnClickListener(new myButtonListener());

		if (savedInstanceState == null) {
			getSupportFragmentManager().beginTransaction()
					.add(R.id.container, new PlaceholderFragment()).commit();
		}
	}
	
	class myButtonListener implements OnClickListener{

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Button myButton = (Button)findViewById(R.id.button1);
			myButton.setText("HelloYyxhhx");
			
		}
		
	}

	@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;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	/**
	 * A placeholder fragment containing a simple view.
	 */
	public static class PlaceholderFragment extends Fragment {

		public PlaceholderFragment() {
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_main, container,
					false);
			return rootView;
		}
	}

}
程序初始界面如下
bubuko.com,布布扣

点击下Button

bubuko.com,布布扣

Android的学习3-初识Activity,布布扣,bubuko.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!