移动智能开发练习题

  1. 编写一个程序,在文本框中输入用户名和密码,分别输入admin和123456提示登录成功,否则提示出错。
    @Override
    public void onClick(View v) {
    // TODO Auto-generated method stub
    String name = etName.getText().toString();
    String word = etWord.getText().toString();
    if(name.equals(“admin”)&&word.equals(“123456”)){
    Toast.makeText(MainActivity.this,“登陆成功”, 1000).show();
    }else{
    Toast.makeText(MainActivity.this,“用户名或者密码错误”, 1000).show();
    }
    }

  2. 编写一个程序,在两个文本框中分别输入两个数,点击按钮,在TextView控件中显示最大的那个数。
    @Override
    public void onClick(View v) {
    // TODO Auto-generated method stub
    int a = Integer.valueOf(etFir.getText().toString());
    int b = Integer.valueOf(etFir.getText().toString());
    if (a>b){
    tvMax.setText(a+"");
    }
    else{
    tvMax.setText(b+"");
    }
    }

  3. 编写一个程序,在两个文本框中分别输入两个数,点击按钮,在TextView控件中显示最小的那个数。

  4. 编写一个程序,在两个文本框中分别输入两个数,点击按钮,在TextView控件中显示两个数的和。
    EditText etFirst,etSecond;
    TextView tvSum;
    Button btnSum;
    @Override
    public void onClick(View v) {
    // TODO Auto-generated method stub
    Integer First = Integer.valueOf(etFirst.getText().toString());
    Integer Second = Integer.valueOf(etSecond.getText().toString());
    Integer Sum = First+Second;
    tvSum.setText(Integer.toString(Sum));}

  5. 编写一个程序,在两个文本框中分别输入两个数,点击按钮,在TextView控件中显示两个数的差。

  6. 编写一个程序,在两个文本框中分别输入两个数,点击按钮,在TextView控件中显示两个数的乘积。

  7. 编写一个程序,在两个文本框中分别输入两个整数,点击按钮,在TextView控件中显示两个数整除的商。

  8. 编写一个程序,在两个文本框中分别输入两个整数,点击按钮,在TextView控件中显示两个数整除的余数。

  9. 编写一个程序,在一个文本框中输入3个数相加,如:23+8+9,点击”求和”按钮,将求出的结果显示到TextView中。
    public class MainActivity extends Activity implements OnClickListener{

    TextView tv;
    EditText et;
    Button btnOk;
    int sum=0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    tv = (TextView) findViewById(R.id.tv);
    et = (EditText) findViewById(R.id.et);
    btnOk = (Button) findViewById(R.id.btnOk);
    btnOk.setOnClickListener(this);
    }
    @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 void onClick(View v) {
    // TODO Auto-generated method stub
    String num = et.getText().toString();//获得et中的内容ֵ
    String[] str=num.split("\+");//将num根据\划分出三个数存到str这个数组中
    for(int i=0;i<str.length;i++){
    sum=sum+Integer.parseInt(str[i]);//求和
    }
    tv.setText(String.valueOf(sum));
    }
    }

  10. 编写一个程序,包含一个TextView和一个Button,点击Button,TextView中文字的颜色就会改变,颜色可以随机产生。
    public class MainActivity extends Activity implements OnClickListener{

    TextView tv;
    Button btn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    tv = (TextView) findViewById(R.id.tv);
    btn = (Button) findViewById(R.id.btn);
    btn.setOnClickListener(this);
    }

    @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 void onClick(View arg0) {
    // TODO Auto-generated method stub

    Random random = new Random();
    int red=random.nextInt(256);
    int green=random.nextInt(256);
    int blue=random.nextInt(256);
    //
    int color=Color.rgb(red, green, blue);
    tv.setTextColor(color);
    

    }

}
11. 编写一个程序,包含一个TextView和一个Button,点击Button,TextView中文字的颜色就会改变,颜色可以是预先定义好的若干颜色。
在values下新建一个color.xml文件:

<?xml version="1.0" encoding="utf-8"?> #ff0000 #00ff00 #ccc MainActivity: public class MainActivity extends Activity implements OnClickListener {
TextView tv;
Button btn;
int arry[];//定义一个数组存放颜色
int i;
@Override
protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_main);
	tv = (TextView) findViewById(R.id.tv);
	btn = (Button) findViewById(R.id.btn);
	btn.setOnClickListener(this);
	//将颜色加入到数组中
	arry = new int[]{R.drawable.red,R.drawable.green,R.drawable.gray};
	
}

@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 void onClick(View v) {
	// TODO Auto-generated method stub
	int color = 0;
	for(i=0;i<arry.length;i++){
		color = getResources().getColor(arry[i]);
		tv.setTextColor(color);
	}
	
}

}

  1. 编写一个程序,在一个文本框中输入货号,比如:A-2,则在数量输入框中自动填充上数值2。
    public class MainActivity extends Activity implements OnFocusChangeListener{
    EditText et1,et2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    et1 = (EditText) findViewById(R.id.et1);
    et2 = (EditText) findViewById(R.id.et2);
    et1.setOnFocusChangeListener(this);
    }
    @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 void onFocusChange(View v, boolean hasFocus) {
    // TODO Auto-generated method stub
    String str = et1.getText().toString();
    String[] str1 = str.split("-");
    et2.setText(str1[str1.length-1]);

    }

}
13. 编写一个程序,生成两个50-100之间的随机数,并进行加法运算。
public class MainActivity extends Activity {

TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    tv = (TextView) findViewById(R.id.tv);
    Random r1 = new Random();
    Random r2 = new Random();
    int n1 = r1.nextInt(50)+50;//nextInt(50)随机生成0-50之间的整数
    int n2 = r2.nextInt(50)+50;
    int sum=n1+n2;
    tv.setText(String.valueOf(n1+"+"+n2+"="+sum));
}
@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;
}

}
14. 编写一个程序,输入一个数,计算这个数的阶乘并显示。
public class MainActivity extends Activity implements OnClickListener{
TextView tv;
EditText et;
Button btn;
int sum=1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tv);
et = (EditText) findViewById(R.id.et);
btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(this);
}
@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 void onClick(View v) {
// TODO Auto-generated method stub
int s = Integer.parseInt(et.getText().toString());
for(int i=1;i<=s;i++){
sum = sum*i;
}
tv.setText(String.valueOf(sum));
}

}
15. 编写一个程序,实现文本框获得焦点时,文本框变成红边白底,否则黑边白底;按钮按下时变成灰底红字,否则白底黑字。
MainActivity:
public class MainActivity extends Activity {

EditText et,et2;
Button btn;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    et=(EditText)findViewById(R.id.et);
    et2=(EditText)findViewById(R.id.et2);
    btn=(Button)findViewById(R.id.btn);
}
@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;
}

}
Activity_main:

<EditText
    android:id="@+id/et"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="72dp"
    android:ems="10"
    android:background="@drawable/et_selector" />

<EditText
    android:id="@+id/et2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/et"
    android:layout_below="@+id/et"
    android:layout_marginTop="33dp"
    android:ems="10"
    android:background="@drawable/et_selector"
    <requestFocus />
</EditText>

<Button
    android:id="@+id/btn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignRight="@+id/et2"
    android:layout_below="@+id/et2"
    android:layout_marginRight="59dp"
    android:layout_marginTop="30dp"
    android:text="变色"
            android:background="@drawable/btn_selector"
            android:textColor="@color/text_selector"
             />
Values中创建color.xml: <?xml version="1.0" encoding="utf-8"?> #ff0000 #666666 #ffffff #000000 Drawable-hdpi创建btn_selector: <?xml version="1.0" encoding="utf-8"?> Drawable-hdpi创建et_false: <?xml version="1.0" encoding="utf-8"?> Drawable-hdpi创建et_true: <?xml version="1.0" encoding="utf-8"?> Drawable-hdpi创建et_selector: <?xml version="1.0" encoding="utf-8"?> 新建color文件在color中创建text_selector: <?xml version="1.0" encoding="utf-8"?> 16. 设计一个身高计算器,计算公式: 男孩:(父亲身高+母亲身高)×0.54cm 女孩:(父亲身高×0.923+母亲身高)÷2cm。 public class MainActivity extends Activity implements OnClickListener{
TextView tvFather,tvMother,tvBoy,tvGirl;
EditText etFather,etMother,etBoy,etGirl;
Button btnBoy;//,btnGirl;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    tvFather = (TextView) findViewById(R.id.tvFather);
    tvMother = (TextView) findViewById(R.id.tvMother);
    etFather = (EditText) findViewById(R.id.etFather);
    etMother = (EditText) findViewById(R.id.etMother);
    etBoy = (EditText) findViewById(R.id.etBoy);
    etGirl = (EditText) findViewById(R.id.etGirl);
    btnBoy = (Button) findViewById(R.id.btnBoy);
    //btnGirl = (Button) findViewById(R.id.btnGirl);
    btnBoy.setOnClickListener(this);
    //btnGirl.setOnClickListener(this);
}


@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 void onClick(View v) {
	// TODO Auto-generated method stub
	int father = Integer.parseInt(etFather.getText().toString());
	int mother = Integer.parseInt(etMother.getText().toString());
	String boy = String.valueOf((father+mother)*0.54);
	String girl = String.valueOf((father*0.923+mother)/2);
	etBoy.setText(boy);
	etGirl.setText(girl);
	
	
}

}
二、

  1. 编写一个程序,可以显示实时时间,按返回时有弹出对话框提示是否退出程序,按确认后退出程序。
    public class MainActivity extends Activity implements OnClickListener{

    Button button;
    TextView tv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    button = (Button) findViewById(R.id.button);
    tv = (TextView) findViewById(R.id.tv);
    button.setOnClickListener(this);
    //显示当前时间
    Calendar calendar = Calendar.getInstance();
    int year = calendar.get(Calendar.YEAR);
    int month = calendar.get(Calendar.MONTH)+1;
    int day = calendar.get(Calendar.DAY_OF_MONTH);
    int hour = calendar.get(Calendar.HOUR_OF_DAY)+13;
    int minute = calendar.get(Calendar.MINUTE);
    int second = calendar.get(Calendar.SECOND);
    tv.setText(year+“年”+month+“月”+day+“日”+hour+“时”+minute+“分”+second+“秒”);

    }
    //点击按钮选择是否退出程序
    @Override
    public void onClick(View v) {
    // TODO Auto-generated method stub
    AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this)
    .setTitle(“退出程序”)
    .setMessage(“是否退出程序”)
    .setPositiveButton(“确定”, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialogInterface, int i) {
    finish();
    }
    })
    .setNegativeButton(“取消”, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialogInterface, int i) {
    return;
    }
    }).create();
    alertDialog.show();

    }

}
2. 编写一个程序,按下按钮后间隔10秒自动弹出一个Toast显示当前时间,按返回时有弹出对话框提示是否退出程序,按确认后退出程序。
public class MainActivity extends Activity implements OnClickListener{

Button btn,btnTime;
private SimpleDateFormat df;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btn = (Button) findViewById(R.id.btn);
    btnTime = (Button) findViewById(R.id.btnTime);
    btn.setOnClickListener(this);
    btnTime.setOnClickListener(this);

  
}
@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 void onClick(View v){
	// TODO Auto-generated method stub
	switch(v.getId()){
	case R.id.btn:
		//显示当前时间
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH)+1;
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int hour = calendar.get(Calendar.HOUR_OF_DAY)+13;
        int minute = calendar.get(Calendar.MINUTE);
        int second = calendar.get(Calendar.SECOND);
        String time = year+"年"+month+"月"+day+"日"+hour+"时"+minute+"分"+second+"秒";
		new AlertDialog.Builder(MainActivity.this).setMessage(time).setPositiveButton("返回", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				new AlertDialog.Builder(MainActivity.this).setMessage("是否退出程序?")
				.setNegativeButton("否", null)
				.setPositiveButton("是", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						finish();
					}
				}).show();
			}
		}).show();break;
		default:
			break;
		case R.id.btnTime:
			//显示当前时间
	        Calendar calendar2 = Calendar.getInstance();
	        int year2 = calendar2.get(Calendar.YEAR);
	        int month2 = calendar2.get(Calendar.MONTH)+1;
	        int day2 = calendar2.get(Calendar.DAY_OF_MONTH);
	        int hour2 = calendar2.get(Calendar.HOUR_OF_DAY)+13;
	        int minute2 = calendar2.get(Calendar.MINUTE);
	        int second2 = calendar2.get(Calendar.SECOND);
	        final String time2 = year2+"年"+month2+"月"+day2+"日"+hour2+"时"+minute2+"分"+second2+"秒";
	        
	        Handler handler = new Handler();
	        handler.postDelayed(new Runnable(){

				@Override
				public void run() {
					// TODO Auto-generated method stub
					Toast.makeText(MainActivity.this,time2, 10000).show();
				}
	        	
	        }, 10000);
			
		
	}
	
}

}

  1. 编写一个程序,实现一个登录界面,在登录界面中包含一个复选按钮“记住我”,选择时保存用户名和密码,否则不保存,打开登录界面时,如果有保存的用户名和密码,则将保存的用户名和密码显示到对应控件中。

  2. 编写一个程序,实现一个日记功能,将写好的日记保存到设备内部中,点击浏览的时候查看日记内容。
    Activity_main:

     <requestFocus />
    

MainActivity: public class MainActivity extends Activity implements OnClickListener{
TextView tvName,tvContent;
EditText etName,etContent;
Button btnOpen,btnSave;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    tvName=(TextView) findViewById(R.id.tvName);
    tvContent=(TextView) findViewById(R.id.tvContent);
    etName=(EditText) findViewById(R.id.etName);
    etContent=(EditText) findViewById(R.id.etContent);
    btnOpen=(Button) findViewById(R.id.btnOpen);
    btnSave=(Button) findViewById(R.id.btnSave);
    btnOpen.setOnClickListener(this);
    btnSave.setOnClickListener(this);
}

@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 void onClick(View v) {
	// TODO Auto-generated method stub
	switch (v.getId()) {
	case R.id.btnOpen:
		OpenFile();//自定义一个打开文件的方法
		break;
	case R.id.btnSave:
		SaveFile();//自定义一个保存文件的方法
		break;
	}
}

//内部文件存储写入
	private void SaveFile() {
		String name=etName.getText().toString()+".txt";
		String content=etContent.getText().toString();
		try {
			FileOutputStream fos = openFileOutput(name, MODE_PRIVATE);
			fos.write(content.getBytes());
			fos.close();//内部存储-写入的关闭
			Toast.makeText(this, "success", 1000).show();//保存成功提示success
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	//内部文件存储读取
	private void OpenFile() {
		String name=etName.getText().toString()+".txt";
		try {
			FileInputStream fis = openFileInput(name);
			byte[] buffer=new byte[fis.available()];
			fis.read(buffer);
			String content=new String(buffer);
			etContent.setText(content);
			fis.close();//内部存储-读取的关闭
			Toast.makeText(this, "success", 1000).show();//打开成功提示success
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
5. 编写一个程序,实现一个日记功能,将写好的日记保存到SD卡上,点击浏览的时候查看日记内容。
先给SDK分配内存
Activity_main:(一个文本框,一个输入框,两个按钮分别是保存和浏览)
ActivityMain:
public class MainActivity extends Activity implements OnClickListener{

Button btnSave,btnLook;
EditText et;
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    et = (EditText) findViewById(R.id.et);
    tv = (TextView) findViewById(R.id.tv);
    btnSave = (Button) findViewById(R.id.btnSava);
    btnLook = (Button) findViewById(R.id.btnLook);
    btnSave.setOnClickListener(this);
    btnLook.setOnClickListener(this);
}
@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 void onClick(View v) {
	// TODO Auto-generated method stub
	switch(v.getId()){
	case R.id.btnSava:
		try {
			write(et.getText().toString());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		break;
	case R.id.btnLook:
		String temp;
		try {
			temp = read();
			tv.setText(temp);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		break;
	}
	
}
public String read() throws Exception{
	
	String name = "ss.txt";
	File sdPath = Environment.getExternalStorageDirectory();
	File file = new File(sdPath,name);
	FileInputStream fis = new FileInputStream(file);
	byte[] buffer = new byte[fis.available()];
	fis.read(buffer);
	
	return new String(buffer);
	
}
public void write(String content) throws Exception{
	String name = "ss.txt";
	File sdPath = Environment.getExternalStorageDirectory();
	File file = new File(sdPath,name);
	FileOutputStream fos = new FileOutputStream(file);
	fos.write(content.getBytes());
	fos.close();
	Toast.makeText(this, "存到sd卡", 1000).show();
}

}
AndroidManifest:


  1. 编写一个程序,通过Handler和Thread或Runnable实现以10秒时间显示完进度条进度。

Activity_main:

<ProgressBar
    android:id="@+id/pb1"
    style="?android:attr/progressBarStyleHorizontal"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_marginLeft="106dp"
    android:layout_marginTop="126dp" />

<TextView
    android:id="@+id/tv1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignRight="@+id/pb1"
    android:layout_below="@+id/pb1"
    android:layout_marginTop="23dp"
    android:text="TextView" />

<Button
    android:id="@+id/btn1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignRight="@+id/tv1"
    android:layout_below="@+id/tv1"
    android:layout_marginTop="30dp"
    android:text="Button" />
ActivityMain: public class MainActivity extends Activity { ProgressBar pb; Button btn; TextView tv; Handler handler = new Handler(){ //handlerMessage(Message msg)子类对象通过该方法接收消息 public void handleMessage(android.os.Message msg) { pb.setProgress(msg.arg1); tv.setText( String.valueOf(msg.arg1) + "%" ); if(msg.arg1>=100){ Toast.makeText(MainActivity.this, "完成", Toast.LENGTH_SHORT).show(); } }; }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); pb = (ProgressBar)findViewById(R.id.pb1); btn = (Button)findViewById(R.id.btn1); tv = (TextView) findViewById(R.id.tv1); btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub pb.setVisibility(View.VISIBLE); new Mythread().start(); } }); }
class Mythread extends Thread{
	public void run(){
		super.run();
		//100次循环*100毫秒=十秒
		//因为这个进度条的长度是1-100
	//所以一秒加载大约进度条的10%
	for(int i=1;i<=100;i++){
			try {
				Thread.sleep(100);
				
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}Message msg = new Message();
			msg.arg1 = i;
			handler.sendMessage(msg);
			
		}
	}
}

}
7. 编写一个程序,通过AsyncTask实现以20秒时间显示完进度条进度。
Activity_main: (放三个textview,一个progressBar,一个按钮)
MainActivity:
public class MainActivity extends Activity implements OnClickListener {

Button btnBegin;
ProgressBar pb;
TextView tv;

@Override
protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_main);
	btnBegin = (Button) findViewById(R.id.btnBegin);
	pb = (ProgressBar) findViewById(R.id.pb);
	tv = (TextView) findViewById(R.id.tv);

	btnBegin.setOnClickListener(this);
}

@Override
public void onClick(View v) {
	// TODO 自动生成的方法存根
	pb.setVisibility(View.VISIBLE);
	new MyTask().execute();//最后输入这一行代码

}

//先建立MyTask类,只输入标黄的方法然后alt+/,方法直接出来
class MyTask extends AsyncTask<String, Integer, String>{

	// 方法1:onPreExecute()
    // 作用:执行 线程任务前的操作
    @Override
    protected void onPreExecute() {
        tv.setText("0%");
        // 执行前显示提示
    }

    // 方法2:doInBackground()
    // 作用:接收输入参数、执行任务中的耗时操作、返回 线程任务执行的结果
    // 此处通过计算从而模拟“加载进度”的情况
	@Override
	protected String doInBackground(String... params) {
		try {
            
            for(int i=1;i<=100;i++) {
                // 可调用publishProgress()显示进度, 之后将执行onProgressUpdate()
                publishProgress(i);
                // 模拟耗时任务
                Thread.sleep(200);
            }
        }catch (InterruptedException e) {
            e.printStackTrace();
        }

        return null;

	}
	
	// 方法3:onProgressUpdate()
    // 作用:在主线程 显示线程任务执行的进度
    @Override
    protected void onProgressUpdate(Integer... progresses) {

        pb.setProgress(progresses[0]);
        tv.setText(progresses[0] + "%");

    }
    
    // 方法4:onPostExecute()
    // 作用:接收线程任务执行结果、将执行结果显示到UI组件
    @Override
    protected void onPostExecute(String result) {
        // 执行完毕后,则更新UI
        Toast.makeText(MainActivity.this, "下载完成", Toast.LENGTH_SHORT).show();
    }
	
	
}

}
8. 编写一个程序,手动绑定列表控件ListView,每条记录中包含图片,名称和描述。
Layout中新建一个list_item.xml文件:

<?xml version="1.0" encoding="utf-8"?>

<ImageView
    android:id="@+id/img"
    android:layout_width="64dp"
    android:layout_height="64dp"
    android:src="@drawable/tb_baidu" />

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical" >
     <TextView
    android:id="@+id/title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="20sp"
    android:text="百度" />
     <TextView
    android:id="@+id/url"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="http://www.baidu.com" />
   <TextView
    android:id="@+id/description"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="12sp"
    android:text="百度网站是一个搜索网站" />
</LinearLayout>

Layout中的activity_main:

<ListView
    android:id="@+id/lvSimple"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true" >
</ListView>
MainActivity: public class MainActivity extends Activity {
ListView lvSimple;
List<Map<String,Object>> list;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ListView lvSimple = (ListView) findViewById(R.id.lvSimple);
    list = getData();
    SimpleAdapter simpleAdapter = 
    		new SimpleAdapter(this,list,
    				R.layout.list_item,
    				new String[] {"img","title","url"},
    				new int[]{R.id.img,R.id.title,R.id.url});
    lvSimple.setAdapter(simpleAdapter);
}
private List<Map<String,Object>> getData()
{
	List<Map<String,Object>> listItem=null;
	listItem=new ArrayList<Map<String,Object>>();
	Map<String,Object> map=new HashMap<String,Object>();
	map.put("img", R.drawable.tb_baidu);
	map.put("title", "百度");
	map.put("url", "http://www.baidu.com");
	map.put("description", "百度是一个搜索网站");
	listItem.add(map);
	
	map=new HashMap<String,Object>();
	map.put("img", R.drawable.tb_netease);
	map.put("title", "网易");
	map.put("url", "http://www.163.com");
	map.put("description", "网易是一个综合网站");
	listItem.add(map);
	
	map=new HashMap<String,Object>();
	map.put("img", R.drawable.tb_sina);
	map.put("title", "新浪");
	map.put("url", "http://www.sina.com.cn");
	map.put("description", "新浪是一个综合网站");
	listItem.add(map);
		
	map=new HashMap<String,Object>();
	map.put("img", R.drawable.tb_tencent);
	map.put("title", "腾讯");
	map.put("url", "http://www.qq.com");
	map.put("description", "腾讯是一个搜索网站");
	listItem.add(map);
	
	return listItem;
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
	// Inflate the menu; this adds items to the action bar if it is present.
	getMenuInflater().inflate(R.menu.simple, menu);
	return true;
}

}
在res下的drawable-hdpi需要四个图片分别命名为tb_baidu tb_netease tb_sina tb_tencent。
9. 编写一个程序,通过使用Service来实现简单的播放器。
在res文件下新建一个文件夹raw在raw中放入音乐.mp3
Activity_main: (放两个按钮)
Mainactivity:
public class MainActivity extends Activity {

Button play,stop;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    play = (Button) findViewById(R.id.play);
    stop = (Button) findViewById(R.id.stop);
    play.setOnClickListener(new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			startService(new Intent(MainActivity.this,MyMusicService.class));
		}
	});
    stop.setOnClickListener(new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			stopService(new Intent(MainActivity.this,MyMusicService.class));
			
		}
	});
}


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

}
在src下新建一个类MyMusicSercive.java:
public class MyMusicService extends Service{

MediaPlayer player;

@Override
public void onCreate() {
	// TODO Auto-generated method stub
	player = MediaPlayer.create(this, R.raw.zpy);
	Log.i("Msg", "create");
	super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
	// TODO Auto-generated method stub
	player.start();
	Log.i("Msg", "start");
	return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
	// TODO Auto-generated method stub
	player.stop();
	Log.i("Msg", "stop");
	super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
	// TODO Auto-generated method stub
	return null;
}

}
在AndroidMainifest.xml文件中加上:

10. 编写一个程序,实现在状态栏提示有新短消息,展开状态栏点击消息时弹出详细信息界面。
activity_main.xml: (放一个按钮)
activity_second.xml:(放一个文本框)
MainActivity:
public class MainActivity extends Activity implements OnClickListener{

Button btnSend;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btnSend = (Button) findViewById(R.id.btnSend);
    btnSend.setOnClickListener(this);
}


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


@SuppressLint("NewApi") @Override
public void onClick(View v) {
	// TODO Auto-generated method stub
	switch(v.getId()){
	case R.id.btnSend:
		NotificationManager Manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
		Notification.Builder builder = new Notification.Builder(this);
		builder.setSmallIcon(R.drawable.ic_launcher);//标记提醒时的图标
		builder.setTicker("Hello");//消息提醒是显示时的内容
		builder.setContentTitle("新消息提醒");//展开状态栏后显示的标题
		builder.setContentText("详细内容");//展开状态栏后显示的内容
		Intent intent = new Intent(this,SecondActivity.class);//传值
		//intent.putExtra("send", "要传递的值");
		//生成PendingIntent对象
		PendingIntent pendingIntent = PendingIntent.getActivity(this, 1, intent, 0);
		//设置跳转页面
		builder.setContentIntent(pendingIntent);
		//获得Notification对象
		Notification notification = builder.build();
		//实现消息提示
		Manager.notify(0,notification);
		break;
	}
	
	
}

}
SecondActivity:
public class SecondActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_second);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
	// Inflate the menu; this adds items to the action bar if it is present.
	getMenuInflater().inflate(R.menu.second, menu);
	return true;
}

}
11. 编写一个程序,实现ListView显示好友列表信息,要求使用BaseAdapter。
编写一个程序,实现ListView显示好友列表信息,要求使用BaseAdapter。
在layout中新建一个item.xml:(放一个TextView就行)

<?xml version="1.0" encoding="utf-8"?>

<TextView
    android:id="@+id/tvName"
    android:layout_width="wrap_content"
    android:layout_height="30dp"
    android:text="adkjaskdfjkasdjfk" />
Activity_main.xml:(放一个ListView就行):
<ListView
    android:id="@+id/lvBase"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true" >
</ListView>
MainActivity: public class MainActivity extends Activity {
ListView lvBase;
String[] friends=new String[] {"徐玉玉","山慧敏","王圆圆","牟韵洁"};
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    lvBase = (ListView) findViewById(R.id.lvBase);
    lvBase.setAdapter(new MyBaseAdapter(this));
}

class MyBaseAdapter extends BaseAdapter{

LayoutInflater inflater;
public MyBaseAdapter(Context context){
	inflater=LayoutInflater.from(context);
}
@Override
public int getCount() {
	// TODO Auto-generated method stub
	return friends.length;
}

@Override
public Object getItem(int position) {
	// TODO Auto-generated method stub
	return friends[position];
}

@Override
public long getItemId(int position) {
	// TODO Auto-generated method stub
	return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
	// TODO Auto-generated method stub
	
	ViewHolder vh;
	if(convertView==null){
		//获取布局文件。inflater:充气机
		convertView=inflater.inflate(R.layout.item, null);
		vh=new ViewHolder();
		vh.tvName = (TextView) convertView.findViewById(R.id.tvName);
		convertView.setTag(vh);
	} 
	else
		vh = (ViewHolder) convertView.getTag();
	//赋值
	vh.tvName.setText(friends[position]);
	return convertView;
}	
//创建ViewHolder类
	class ViewHolder{
		TextView tvName;
}

}

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

}
Values文件下的strings.xml:

<?xml version="1.0" encoding="utf-8"?>
<string name="app_name">T211</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>


 <string-array name="friends">
    <item>好友1</item>
    <item>好友2</item>
    <item>好友3</item>
    <item>好友4</item>
    
</string-array>
<string name="activity_main">MainActivity</string>
12. 编写一个程序,要求如下:至少包含两个activity;第一个activity中的信息可以发送到第二个activity,并可以在第二个activty中呈现。 Activity_main: (放一个输入框跟按钮) Second_main: (放一个文本框) MainActivity: public class MainActivity extends Activity implements OnClickListener{
EditText et;
Button btnSend;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    et = (EditText) findViewById(R.id.et);
    btnSend = (Button) findViewById(R.id.btnSend);
    btnSend.setOnClickListener(new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			String msg = et.getText().toString();
			Intent intent = new Intent(MainActivity.this,SecondActivity.class);
			intent.putExtra("msg", msg);
			startActivity(intent);
		}
	});
}


@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 void onClick(View v) {
	// TODO Auto-generated method stub
	
}

}
SecondActivity:
public class SecondActivity extends Activity {

TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_second);
	tv = (TextView) findViewById(R.id.tv);
	Intent intent = this.getIntent();
	String msg = intent.getStringExtra("msg");
	tv.setText(msg);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
	// Inflate the menu; this adds items to the action bar if it is present.
	getMenuInflater().inflate(R.menu.second, menu);
	return true;
}

}
13. 编写一个程序,要求如下:至少包含两个activity;第一个activity中的信息可以发送到第二个activity,并可以在第二个activty中呈现,并在第二个activity中可以回传数据给第一个activity。
Activity_main: (放一个按钮,一个文本框,一个输入框)
Second_main: (放一个按钮,一个文本框,一个输入框)
MainActivity:
public class MainActivity extends Activity implements OnClickListener{

TextView tvSend;
Button btnSend;
EditText etSend;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    tvSend = (TextView) findViewById(R.id.tvSend);
    btnSend = (Button) findViewById(R.id.btnSend);
    etSend = (EditText) findViewById(R.id.etSend);
    btnSend.setOnClickListener(new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			String msg = etSend.getText().toString();
			Intent intent = new Intent(MainActivity.this,SecondActivity.class);
			intent.putExtra("msg", msg);
			startActivityForResult(intent, 1);
		}
	});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	// TODO Auto-generated method stub
	super.onActivityResult(requestCode, resultCode, data);
	String msgback = data.getStringExtra("msgback");
	tvSend.setText(msgback);
}
@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 void onClick(View v) {
	// TODO Auto-generated method stub
	
}

}
SecondActivity:
public class SecondActivity extends Activity implements OnClickListener{

TextView tvBack;
EditText etBack;
Button btnBack;
Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_second);
	tvBack = (TextView) findViewById(R.id.tvBack);
	btnBack = (Button) findViewById(R.id.btnBack);
    etBack = (EditText) findViewById(R.id.etBack);
    //得到第一个activity传过来的值
    intent = this.getIntent();
    String msg = intent.getStringExtra("msg");
    tvBack.setText(msg);
    //将第二个activity的值传给第一个activity
    btnBack.setOnClickListener(new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			String msg2 = etBack.getText().toString();
			Intent intent2 = new Intent();
			intent2.putExtra("msg2", msg2);
			setResult(1,intent2);
			finish();
		}
	});
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
	// Inflate the menu; this adds items to the action bar if it is present.
	getMenuInflater().inflate(R.menu.second, menu);
	return true;
}

@Override
public void onClick(View v) {
	// TODO Auto-generated method stub
	
}

}
14. 编写一个程序,实现学院输入,包含一个EditText,一个Button,点击Button时弹出一个学院对话框,在对话框中选择一个学院,将选择的学院显示到EditText控件中。
Mainactivity:
public class MainActivity extends Activity implements OnClickListener{

int result = -1;
EditText et;
Button btn;
String[] majors = new String[] {"信息学院","外国语学院","美术学院","音乐学院"};
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    et = (EditText) findViewById(R.id.et);
    btn = (Button) findViewById(R.id.btn);
    btn.setOnClickListener(new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			showSingleDialog();
		}

		
	});
}
public void showSingleDialog() {
	// TODO Auto-generated method stub
	Builder choose = new Builder(MainActivity.this);
	choose.setTitle("请选择一个学院");
	choose.setSingleChoiceItems(majors, 0, new DialogInterface.OnClickListener() {
		
		@Override
		public void onClick(DialogInterface dialog, int which) {
			// TODO Auto-generated method stub
			result = which;
		}
	});
	choose.setPositiveButton("确定", new DialogInterface.OnClickListener() {
		
		@Override
		public void onClick(DialogInterface dialog, int which) {
			// TODO Auto-generated method stub
			et.setText(majors[result]);
		}
	});
	choose.show();
}

@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 void onClick(View v) {
	// TODO Auto-generated method stub
	
}

}

  1. 编写一个程序,使用ProgressDialog设计一个水平进度条,并以10秒时间显示完进度条进度。
    见第六题

  2. 编写一个程序,实现Spinner显示学院信息,要求使用BaseAdapter。
    使用BaseAdapter:
    Activity_main :(放一个文本框,一个spinner)
    MainActivity:
    public class MainActivity extends Activity {

    Spinner spMajor;
    TextView tvMajor;
    String majors[] = new String[] {“信息学院”,“美术学院”,“音乐学院”,“外国语学院”};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    spMajor = (Spinner) findViewById(R.id.spMajor);
    tvMajor = (TextView) findViewById(R.id.tvMajor);

    BaseAdapter adapter=new MyBaseAdapter();
    spMajor.setAdapter(adapter);
    spMajor.setOnItemSelectedListener(new OnItemSelectedListener() {
    
    	@Override
    	public void onItemSelected(AdapterView<?> arg0, View arg1,
    			int position, long id) {
    		// TODO Auto-generated method stub
    		String str = (String) spMajor.getItemAtPosition(position);
    		//Toast.makeText(MainActivity.this, str, 1000).show();
    		tvMajor.setText(str);
    	}
    
    	@Override
    	public void onNothingSelected(AdapterView<?> arg0) {
    		// TODO Auto-generated method stub
    		
    	}
    });
    

    }
    class MyBaseAdapter extends BaseAdapter{

    @Override
    public int getCount() {
    // TODO Auto-generated method stub
    return majors.length;
    }

    @Override
    public Object getItem(int position) {
    // TODO Auto-generated method stub
    return majors[position];
    }

    @Override
    public long getItemId(int position) {
    // TODO Auto-generated method stub
    return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    TextView textview = new TextView(MainActivity.this);
    textview.setText(majors[position]);
    return textview;

    }

}

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

}
使用ArrayAdapter:
Activity_main :(放一个文本框,一个spinner)
MainActivity:
public class MainActivity extends Activity {

Spinner spMajor;
TextView tvMajor;
String majors[] = new String[] {"信息学院","美术学院","音乐学院","外国语学院"};
ArrayAdapter<String> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final Spinner spMajor = (Spinner) findViewById(R.id.spMajor);
    tvMajor = (TextView) findViewById(R.id.tvMajor);
    adapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_spinner_item,majors);
    spMajor.setAdapter(adapter);
    spMajor.setOnItemSelectedListener(new OnItemSelectedListener() {

		@Override
		public void onItemSelected(AdapterView<?> arg0, View arg1,
				int position, long id) {
			// TODO Auto-generated method stub
			String str = (String) spMajor.getItemAtPosition(position);
			//Toast.makeText(MainActivity.this, str, 1000).show();
			tvMajor.setText(str);
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub
			
		}
	});
}
@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;
}

}

  1. 编写一个程序,实现图片的浏览,向左滑动显示下一张图片,向右滑动显示上一张图片。
    在res文件下的drawable-hdpi放三张图:
    activity_main: (放一个ImageView)
    MainActivity:
    public class MainActivity extends Activity {

    ImageView img;
    int index = 0;
    int touchX,touchY;
    int upX,upY;
    int moveX,moveY;
    int[] images={R.drawable.p1,R.drawable.p2,R.drawable.p3};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //img.setImageResource(images[index]);
    img = (ImageView) findViewById(R.id.img);

    }

    public boolean onTouchEvent(MotionEvent event){
    switch(event.getAction()){
    case MotionEvent.ACTION_DOWN:
    //记录触摸点坐标
    touchX = (int) event.getX();;
    touchY = (int) event.getY();
    break;
    case MotionEvent.ACTION_UP:
    //记录松开点坐标
    upX = (int) event.getX();
    upY = (int) event.getY();
    //计算偏移量
    moveX = upX-touchX;
    moveY = touchX-upX;
    if(moveX>50){
    Toast.makeText(MainActivity.this, “右滑动”, 1000).show();
    index = index-1;
    }
    if(moveY>50){
    Toast.makeText(MainActivity.this, “左滑动”, 1000).show();
    index = index+1;

    	}
    	if(index>2){
    		index=0;
    	}
    	if(index<0){
    		index=2;
    	}
    	img.setImageResource(images[index]);
    }
    return super.onTouchEvent(event);
    

    }

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

}

  1. 编写一个程序,列出所有SD卡上的txt文件,将文件名称显示到LsitView控件上。
    Layout中建activity_main和item.xml
    activity_main:(建ListView!!!)


    item.xml:

    MainActivity:
    public class MainActivity extends Activity {
    ListView lv;
    List<Map<String, String>> names;
    @Override
    protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    lv = (ListView) findViewById( R.id.lv);
    names = new ArrayList<Map<String,String>>();
    File path = Environment.getExternalStorageDirectory();
    //先去sd卡里面存点txt文件
    try {write();} catch (Exception e) {e.printStackTrace();}
    File files[] = path.listFiles();
    getFileName(files);
    SimpleAdapter adapter = new SimpleAdapter(
    this,
    names,
    R.layout.item,
    new String[] { “name” },
    new int[] {R.id.tvName}
    );
    lv.setAdapter(adapter);
    //这个地方不能用lv.setOnItemSelectedListener(listener);
    lv.setOnItemClickListener(new OnItemClickListener() { @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) { Toast.makeText(
    MainActivity.this,
    “内容为” + names.get(position).get(“name”),
    Toast.LENGTH_SHORT
    ).show();
    }
    });
    }
    public void getFileName(File[] files) {
    if(files != null) {
    for(File file : files) {
    if(file.isDirectory()) {
    getFileName(file.listFiles());
    }else {
    Map map = new HashMap();
    String fileName = file.getName();
    if(fileName.endsWith(".txt")) {
    map.put(“name”, fileName );
    names.add(map);
    }}}}}
    //先去sd卡里面添加txt文档
    public void write() throws Exception {
    String name,content;
    File SDPath = Environment.getExternalStorageDirectory();
    File file;
    FileOutputStream fos;

name = “java学习.txt”;
content = “123”;
file = new File(SDPath, name);
fos = new FileOutputStream(file);
fos.write(content.getBytes());
fos.close();

name = “c语言学习.txt”;
content = “456”;
file = new File(SDPath, name);
fos = new FileOutputStream(file);
fos.write(content.getBytes());
fos.close();

name = “python学习.txt”;
content = “789”;
file = new File(SDPath, name);
fos = new FileOutputStream(file);
fos.write(content.getBytes());
fos.close();
} }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值