Android基础小程序
来源:互联网 发布:黑玫瑰籽海藻面膜 淘宝 编辑:程序博客网 时间:2024/05/22 00:05
1、简单的计数器
xml布局:
Activity代码:
public class MainActivity extends Activity { TextView tv; Button add,sub,reset; int count; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv=(TextView) findViewById(R.id.tv); //关联xml文件中的TextView add=(Button)findViewById(R.id.add); sub=(Button)findViewById(R.id.sub); reset=(Button)findViewById(R.id.reset); count=0; add.setOnClickListener(new View.OnClickListener(){ //Add按钮监听 @Override public void onClick(View v) { count++; tv.setText("The total is "+count); } }); sub.setOnClickListener(new View.OnClickListener(){ //Sub按钮监听 @Override public void onClick(View v) { count--; tv.setText("The total is "+count); } }); reset.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { count=0; tv.setText("The total is 0"); } }); }}
2、起始界面的实现
xml布局:首先需添加一张背景图片至res/drawable中,接着在xml文件中添加
android:background="@drawable/文件名(无需后缀)"Activity代码:
public class flash extends Activity{ MediaPlayer mp; //引用MediaPlay实现音乐播放 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.flash); mp = MediaPlayer.create(this,R.raw.bgm); //音乐文件存放路径为res/raw中(若无raw文件夹则创建) mp.start(); //音乐开始播放 Thread timer = new Thread(){ //创建一个线程 public void run(){ try { sleep(2000); //起始界面存在2秒 } catch (InterruptedException e) { e.printStackTrace(); }finally { Intent fl = new Intent("android.intent.action.MainMenu"); //采用Intent来启动主界面的Activity startActivity(fl); } } }; timer.start(); //线程启动 } @Override protected void onPause() { //引用onPause()方法结束当前Activity super.onPause(); mp.release(); //需释放,若不执行此操作,则会一直播放,直到结束进程为止 finish(); //结束此Activity }}
3、使用ListActivity创建列表菜单
效果图:
Activity代码:
public class MainMenu extends ListActivity { //继承ListActivity //创建菜单列表数组 String classes[] = {"MainActivity","lifeActivity","TextPlay","Data","SharedPrefs","SimpleBrowser"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setListAdapter(new ArrayAdapter<String>(MainMenu.this,android.R.layout.simple_list_item_1,classes)); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { //重写onListItemClick()方法 super.onListItemClick(l, v, position, id); String classStr = classes[position]; //记录菜单顺序 try { Class ourClass = Class.forName("com.example.jason.myapplication."+classStr); Intent startA = new Intent(this,ourClass); //class名的方式指定Activity启动 startActivity(startA); } catch (ClassNotFoundException e) { e.printStackTrace(); } }}
4、布局的简单设计
xml布局代码及视图:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="20dp"> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textPersonName" android:hint="input text" android:ems="10" android:id="@+id/etCommand" /><LinearLayout android:layout_height="wrap_content" android:layout_width="match_parent" android:weightSum="100"> <Button android:text="Try the command" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="20" android:id="@+id/btCommand" /> <ToggleButton android:text="ToggleButton" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="80" android:id="@+id/tbStatus" /></LinearLayout> <TextView android:text="TextView" android:textSize="30dp" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/tvResult" /></LinearLayout>Activity代码:
public class TextPlay extends Activity { EditText etCommand; ToggleButton tbStatus; Button btCommand; TextView tvResult; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.text_play); etCommand = (EditText)findViewById(R.id.etCommand); tbStatus = (ToggleButton)findViewById(R.id.tbStatus); btCommand = (Button)findViewById(R.id.btCommand); tvResult = (TextView)findViewById(R.id.tvResult); btCommand.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { String check = etCommand.getText().toString(); tvResult.setText(check); String color = tvResult.getTextColors().toString(); //获取TextView中的字体颜色 if(color.contentEquals("BLACK")==false){ //如果输入字体为“BLACK” tvResult.setTextColor(Color.BLACK); //设置字体颜色为黑色 } if(check.contentEquals("left")){ tvResult.setGravity(Gravity.LEFT); //设置TextView在布局中的左边 }else if(check.contentEquals("right")){ tvResult.setGravity(Gravity.RIGHT); }else if(check.contentEquals("center")){ tvResult.setGravity(Gravity.CENTER); }else if(check.contentEquals("blue")){ tvResult.setTextColor(Color.BLUE); }else if(check.contentEquals("yellow")){ tvResult.setTextColor(Color.YELLOW); }else if(check.contains("haha")){ //如果输入字体含有“haha” Random crazyNum = new Random(); //定义一个随机数 tvResult.setText("HAHA!!!"); tvResult.setTextSize(crazyNum.nextInt(100)); //设置一个[0—100)的伪随机数 //利用RGB设置随机颜色 tvResult.setTextColor(Color.rgb(crazyNum.nextInt(256),crazyNum.nextInt(256),crazyNum.nextInt(256))); switch (crazyNum.nextInt(3)){ case 0:tvResult.setGravity(Gravity.LEFT); break; case 1:tvResult.setGravity(Gravity.RIGHT); break; case 2:tvResult.setGravity(Gravity.CENTER); break; } }else { tvResult.setText("I can't recognize your command"); } } }); tbStatus.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //设置开关按钮的监听事件 if(tbStatus.isChecked()){ //按钮是否被打开 //如果打开,则设置为密码型输入文本 etCommand.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD | InputType.TYPE_CLASS_TEXT); }else { //否则,设置成文本型 etCommand.setInputType(InputType.TYPE_CLASS_TEXT); } } }); }}
5、Activity传递字符
xml布局采用相对布局,其代码与效果图:
(a)
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:text="TextView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/get_tv" android:layout_below="@+id/bSAFR" /> <Button android:text="StartActivity" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/bSA" android:layout_alignRight="@+id/etSend" android:layout_below="@+id/etSend" android:textAllCaps="false" /> <Button android:text="StartForResult" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/bSAFR" android:layout_toLeftOf="@id/bSA" android:layout_alignTop="@id/bSA" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textPersonName" android:ems="10" android:id="@+id/etSend" /></RelativeLayout>
(b)<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:text="How many people are there in our dormitory?" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/tvQuestion" android:textSize="20dp" /> <RadioGroup android:id="@+id/rgAnswers" android:layout_width="wrap_content" android:layout_height="wrap_content" > <RadioButton android:text="four people" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/rbFour" /> <RadioButton android:text="five people" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/rbFive" /> <RadioButton android:text="six people" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/rbSix" /> </RadioGroup> <Button android:text="Return" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/bReturn" /> <TextView android:text="" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/tvOther" /></LinearLayout>
(a)
public class Data extends Activity implements View.OnClickListener { Button bsa,bsafr; EditText send; TextView tvGet; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.get); initialize(); //定义一个初始化的方法 } private void initialize() { bsa = (Button)findViewById(R.id.bSA); bsafr = (Button)findViewById(R.id.bSAFR); send = (EditText)findViewById(R.id.etSend); tvGet = (TextView)findViewById(R.id.get_tv); bsa.setOnClickListener(this); //采用实现接口的方式监听点击 bsafr.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()){ //获取按钮的ID case R.id.bSA: String s = send.getText().toString(); //获取将要发送的字符 Bundle basket = new Bundle(); //创建一个bundle basket.putString("breakfast",s); //bundle中附带一个字符串 Intent it = new Intent(this,OpenedClass.class); //采用Intent跳转到名为OpenedClass的Activity it.putExtras(basket); //采用putExtras方法,传递一个bundle startActivity(it); //开启OpenedClassActivity break; case R.id.bSAFR: String b = send.getText().toString();//同上 Bundle ket = new Bundle(); ket.putString("breakfast",b); Intent i = new Intent(this,OpenedClass.class); i.putExtras(ket); startActivityForResult(i,0); //Activity回传字符串 break; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { //回传后重写onActivityResult方法 super.onActivityResult(requestCode, resultCode, data); if(resultCode==RESULT_OK){ Bundle answer = data.getExtras(); //获取回传的bundle String s = answer.getString("answer"); //从bundle中获取字符串 tvGet.setText(s); //设置到TextView显示 } }}(b)
public class OpenedClass extends Activity implements RadioGroup.OnCheckedChangeListener, View.OnClickListener { RadioGroup selectionList; Button bReturn; TextView question,other; String s; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.send); initialize(); } private void initialize() { selectionList = (RadioGroup)findViewById(R.id.rgAnswers); bReturn = (Button)findViewById(R.id.bReturn); question = (TextView)findViewById(R.id.tvQuestion); other = (TextView)findViewById(R.id.tvOther); selectionList.setOnCheckedChangeListener(this); bReturn.setOnClickListener(this); Bundle basket = getIntent().getExtras(); //接收上一个Activity传递的bundle String q = basket.getString("breakfast"); //取出bundle中的字符串 question.setText(q); //显示到TextView } @Override public void onCheckedChanged(RadioGroup group, int checkedId) { //监听RadioGroup的改变 switch (checkedId){ //根据RadioButton的ID选择 case R.id.rbFour: s = "four people"; break; case R.id.rbFive: s = "five people"; break; case R.id.rbSix: s = "six people"; break; } other.setText(s); //显示到TextView } @Override public void onClick(View v) { //Return按钮的点击监听 Intent answer = new Intent(); Bundle ket = new Bundle(); ket.putString("answer",s); answer.putExtras(ket); //照常采用Intent的putExtras方法发送bundle中绑定的字符 setResult(RESULT_OK,answer); //设置回传的信息 finish(); //结束当前Activity }}
6、 SharedPreferences保存数据
xml布局代码:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textPersonName" android:ems="10" android:id="@+id/etSave" /> <Button android:text="Save" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/bSave" /> <Button android:text="Load" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/bLoad" /> <TextView android:text="Load your data" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/tvLoad" /></LinearLayout>Activity代码:
public class SharedPrefs extends Activity implements View.OnClickListener { Button save,load; TextView show; EditText input; SharedPreferences someData; //定义一个sharedPreferences public static String filename = "MySharedString"; //定义一个静态的存储名 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.sharedpreferences); setupVariables(); someData = getSharedPreferences(filename,0); //获取sharedPreferences中的数据(无论是否存在) } private void setupVariables() { save = (Button)findViewById(R.id.bSave); load = (Button)findViewById(R.id.bLoad); show = (TextView)findViewById(R.id.tvLoad); input = (EditText)findViewById(R.id.etSave); save.setOnClickListener(this); load.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.bSave: String sharedString = input.getText().toString(); SharedPreferences.Editor editor = someData.edit(); //定义editor用于改变数据 editor.putString("sharedString",sharedString); //存入数据 editor.commit(); //执行commit提交 break; case R.id.bLoad: //获取key为sharedString的数据,若异常,则显示Not get String getString = someData.getString("sharedString","Not get"); show.setText(getString); //显示到TextView break; } }}
7、利用WebView浏览网页
xml代码:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"><LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:weightSum="100" > <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="20" android:inputType="textPersonName" android:id="@+id/etSite" /> <Button android:text="Go" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="80" android:id="@+id/bGo" /></LinearLayout> <WebView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/wvShow"/></LinearLayout>Activity代码:
public class SimpleBrowser extends Activity implements View.OnClickListener { //此外还需在mainifests中添加网络权限<uses-permission android:name="android.permission.INTERNET"/> //添加网络权限 Button go; EditText site; WebView webShow; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.simplebrowser); go = (Button)findViewById(R.id.bGo); site = (EditText)findViewById(R.id.etSite); webShow = (WebView)findViewById(R.id.wvShow); go.setOnClickListener(this); webShow.loadUrl("http://www.baidu.com"); //登录百度网页 webShow.setWebViewClient(new OurClient()); //设置覆盖浏览跳转网页(跳转不调用系统浏览器打开) //打开页面时, 自适应屏幕 webShow.getSettings().setLoadWithOverviewMode(true); webShow.getSettings().setUseWideViewPort(true);//设置此属性,可任意比例缩放 } @Override public void onClick(View v) { switch (v.getId()){ case R.id.bGo: String loadSite = site.getText().toString(); webShow.loadUrl(loadSite); break; } } private class OurClient extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { //划线证明此方法已过时 view.loadUrl(url); return true; } }}
0 0
- Android基础小程序
- 小程序 基础组件
- Java基础练习小程序
- C语言基础小程序
- 几个基础的小程序
- 小程序-01基础配置
- Android 基础小知识
- android 基础小知识点
- Android基础小知识
- android box2d小程序
- Android程序小技巧
- android界面小程序
- Android NavigationDrawer 小程序
- Android小程序总结
- android小程序-----SayHello
- Android--计算器小程序
- android记事本小程序
- Android计算器小程序
- Linux运维笔记-文档总结-linux中设备的访问
- hadoop中NameNode、DataNode、Secondary、NameNode、JobTracker TaskTracker介绍
- 数据结构之图的存储
- UTF8批量转ANSI
- 标准化和归一化
- Android基础小程序
- iOS Type Encodings
- TFT_LCD
- Caffe学习笔记(三):cifar10_quick_train_test.prototxt配置文件分析
- 方立勋_30天掌握JavaWeb_回顾&复习
- 关于Java乱码(2)
- JSP<c:forEach >标签属性
- Vim基本操作
- 题目1169:比较奇偶数个数