https://blog.csdn.net/weixin_42429385
1.Activity生命周期
MainActivity.java
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
String tag="lifestyle";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
Log.d(tag,"In the onCreate() event");
}
@Override
protected void onStart() {
super.onStart();
Log.d(tag,"In the onStart() event");
}
@Override
protected void onRestart() {
super.onRestart();
Log.d(tag,"In the onRestart() event");
}
@Override
protected void onResume(){
super.onResume();
Log.d(tag,"In the onResume() event");
}
protected void onPause(){
super.onPause();
Log.d(tag,"In the onPause() event");
}
@Override
protected void onStop() {
super.onStop();
Log.d(tag,"In the onStop() event");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(tag,"In the onDestroy() 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.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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
2.简易计算器
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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="0dp"
android:orientation="horizontal"
android:layout_weight="2"
>
w
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/et_input"
android:textSize="40sp"
/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="horizontal"
android:weightSum="4"
>
<Button
android:id="@+id/btn_left"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#FFFFFF"
android:text="("
android:textSize="30sp" />
<Button
android:id="@+id/btn_right"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#FFFFFF"
android:text=")"
android:textSize="30sp" />
<Button
android:id="@+id/btn_clear"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#ffffff"
android:text="C"
android:textSize="35sp" />
<Button
android:id="@+id/btn_del"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#ffffff"
android:text="Del"
android:textSize="35sp" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:gravity="center"
android:weightSum="4"
>
<Button
android:id="@+id/btn_7"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#cfcccccc"
android:text="7"
android:textSize="30sp" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="8"
android:textSize="30sp"
android:id="@+id/btn_8"
android:layout_weight="1"
android:background="#cfcccccc"/>
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="9"
android:textSize="30sp"
android:id="@+id/btn_9"
android:layout_weight="1"
android:background="#cfcccccc"/>
<Button
android:id="@+id/btn_plus"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#ffffff"
android:text="+"
android:textSize="40sp" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="0dp"
android:orientation="horizontal"
android:layout_weight="1"
android:weightSum="4"
>
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="4"
android:textSize="30sp"
android:id="@+id/btn_4"
android:layout_weight="1"
android:background="#cfcccccc"/>
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="5"
android:textSize="30sp"
android:id="@+id/btn_5"
android:layout_weight="1"
android:background="#cfcccccc"/>
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="6"
android:textSize="30sp"
android:id="@+id/btn_6"
android:layout_weight="1"
android:background="#cfcccccc"/>
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="-"
android:textSize="50sp"
android:id="@+id/btn_minus"
android:layout_weight="1"
android:background="#ffffff"/>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="0dp"
android:orientation="horizontal"
android:layout_weight="1"
android:weightSum="4"
>
<Button
android:id="@+id/btn_1"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#cfcccccc"
android:text="1"
android:textSize="30sp" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="2"
android:textSize="30sp"
android:id="@+id/btn_2"
android:layout_weight="1"
android:background="#cfcccccc"/>
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="3"
android:textSize="30sp"
android:id="@+id/btn_3"
android:layout_weight="1"
android:background="#cfcccccc"/>
<Button
android:id="@+id/btn_multiply"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#ffffff"
android:text="*"
android:textSize="40sp" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="0dp"
android:orientation="horizontal"
android:layout_weight="1"
android:weightSum="4"
>
<Button
android:id="@+id/btn_point"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#99CCFF"
android:text="."
android:textSize="40sp" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="0"
android:textSize="30sp"
android:id="@+id/btn_0"
android:background="#cfcccccc"
android:layout_weight="1" />
<Button
android:id="@+id/btn_equal"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#99CCFF"
android:text="="
android:textSize="30sp" />
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="/"
android:textSize="40sp"
android:id="@+id/btn_divide"
android:layout_weight="1"
android:background="#ffffff"/>
</LinearLayout>
</LinearLayout>
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Arrays;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button btn_0;
Button btn_1;
Button btn_2;
Button btn_3;
Button btn_4;
Button btn_5;
Button btn_6;
Button btn_7;
Button btn_8;
Button btn_9;
Button btn_point;
Button btn_clear;
Button btn_del;
Button btn_plus;
Button btn_minus;
Button btn_multiply;
Button btn_divide;
Button btn_equal;
Button btn_left;
Button btn_right;
private TextView et_input;
private StringBuilder pending = new StringBuilder();
private void initView() {
btn_0 = (Button) findViewById(R.id.btn_0);
btn_1 = (Button) findViewById(R.id.btn_1);
btn_2 = (Button) findViewById(R.id.btn_2);
btn_3 = (Button) findViewById(R.id.btn_3);
btn_4 = (Button) findViewById(R.id.btn_4);
btn_5 = (Button) findViewById(R.id.btn_5);
btn_6 = (Button) findViewById(R.id.btn_6);
btn_7 = (Button) findViewById(R.id.btn_7);
btn_8 = (Button) findViewById(R.id.btn_8);
btn_9 = (Button) findViewById(R.id.btn_9);
btn_point = (Button) findViewById(R.id.btn_point);
btn_clear = (Button) findViewById(R.id.btn_clear);
btn_del = (Button) findViewById(R.id.btn_del);
btn_plus = (Button) findViewById(R.id.btn_plus);
btn_minus = (Button) findViewById(R.id.btn_minus);
btn_multiply = (Button) findViewById(R.id.btn_multiply);
btn_divide = (Button) findViewById(R.id.btn_divide);
btn_equal = (Button) findViewById(R.id.btn_equal);
et_input = (TextView) findViewById(R.id.et_input);
btn_left = (Button) findViewById(R.id.btn_left);
btn_right = (Button) findViewById(R.id.btn_right);
btn_0.setOnClickListener(this);
btn_1.setOnClickListener(this);
btn_2.setOnClickListener(this);
btn_3.setOnClickListener(this);
btn_4.setOnClickListener(this);
btn_5.setOnClickListener(this);
btn_6.setOnClickListener(this);
btn_7.setOnClickListener(this);
btn_8.setOnClickListener(this);
btn_9.setOnClickListener(this);
btn_point.setOnClickListener(this);
btn_plus.setOnClickListener(this);
btn_equal.setOnClickListener(this);
btn_minus.setOnClickListener(this);
btn_multiply.setOnClickListener(this);
btn_del.setOnClickListener(this);
btn_divide.setOnClickListener(this);
btn_clear.setOnClickListener(this);
btn_divide.setOnClickListener(this);
btn_left.setOnClickListener(this);
btn_right.setOnClickListener(this);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
public void onClick(View v) {
int last = 0;
if(pending.length()!=0)
{
last = pending.codePointAt(pending.length()-1);
}
switch (v.getId())
{
case R.id.btn_0:
pending = pending.append("0");
et_input.setText(pending);
break;
case R.id.btn_1:
pending = pending.append("1");
et_input.setText(pending);
break;
case R.id.btn_2:
pending = pending.append("2");
et_input.setText(pending);
break;
case R.id.btn_3:
pending = pending.append("3");
et_input.setText(pending);
break;
case R.id.btn_4:
pending = pending.append("4");
et_input.setText(pending);
break;
case R.id.btn_5:
pending = pending.append("5");
et_input.setText(pending);
break;
case R.id.btn_6:
pending = pending.append("6");
et_input.setText(pending);
break;
case R.id.btn_7:
pending = pending.append("7");
et_input.setText(pending);
break;
case R.id.btn_8:
pending = pending.append("8");
et_input.setText(pending);
break;
case R.id.btn_9:
pending = pending.append("9");
et_input.setText(pending);
break;
case R.id.btn_plus:
pending = pending.append("+");
et_input.setText(pending);
break;
case R.id.btn_minus:
pending = pending.append("-");
et_input.setText(pending);
break;
case R.id.btn_multiply:
pending = pending.append("*");
et_input.setText(pending);
break;
case R.id.btn_divide:
pending = pending.append("/");
et_input.setText(pending);
break;
case R.id.btn_point:
if (judje1())
{
pending = pending.append(".");
et_input.setText(pending);
}
break;
case R.id.btn_right:// )右括号
if((last>='0' &&last<='9'||last==')')&&judje2()==1)
{
pending = pending.append(")");
et_input.setText(pending);
}
break;
case R.id.btn_left:// (左括号
if((last!='(')||(last<='0' &&last>='9'))
{
pending = pending.append("(");
et_input.setText(pending);
}
break;
case R.id.btn_del: //删除
if (pending.length() != 0)
{
pending = pending.delete(pending.length() - 1, pending.length());
et_input.setText(pending);
}
break;
case R.id.btn_clear: //清空
pending = pending.delete(0, pending.length());
et_input.setText(pending);
break;
case R.id.btn_equal: // =等于
if ((pending.length() > 1))
{
Function inf = new Function();
String jieguo;
try
{
String a = inf.toSuffix(pending);
jieguo = inf.dealEquation(a);
}
catch (Exception ex)
{
jieguo = "出错";
}
et_input.setText(pending + "=" + jieguo);
pending = pending.delete(0, pending.length());
if (Character.isDigit(jieguo.charAt(0)))
{
pending = pending.append(jieguo);
}
}
break;
default:
break;
}
}
private boolean judje1() {
String a = "+-*/.";
int[] b = new int[a.length()];
int max;
for (int i = 0; i < a.length(); i++)
{
String c = "" + a.charAt(i);
b[i] = pending.lastIndexOf(c);
}
Arrays.sort(b);
if (b[a.length() - 1] == -1)
{
max = 0;
}
else
{
max = b[a.length() - 1];
}
if (pending.indexOf(".", max) == -1)
{
return true;
}
else
{
return false;
}
}
private int judje2(){
int a=0,b=0;
for(int i = 0 ; i < pending.length() ;i++)
{
if(pending.charAt(i)=='(' )
{
a++;
}
if(pending.charAt(i)==')' )
{
b++;
}
}
if(a == b)
return 0;
if(a > b)
return 1;
return 2;
}
}
Function.java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.lang.*;
public class Function {
private static final Map<Character,Integer> basic =new HashMap<Character, Integer>();
static {
basic.put('-',1);
basic.put('+', 1);
basic.put('*', 2);
basic.put('/', 2);
basic.put('(', 0);
}
public String toSuffix(StringBuilder infix){
List<String> queue = new ArrayList<String>();
List<Character> stack = new ArrayList<Character>();
char[] charArr = infix.substring(0,infix.length()).trim().toCharArray();
String standard = "*/+-()";
char ch = '&';
int len = 0;
for (int i = 0; i < charArr.length; i++)
{
ch = charArr[i];
if(Character.isDigit(ch))
{
len++;
}
else if(ch == '.')
{
len++;
}
else if(standard.indexOf(ch) != -1)
{
if(len > 0)
{
queue.add(String.valueOf(Arrays.copyOfRange(charArr, i - len, i)));
len = 0;
}
if(ch == '(')
{
stack.add(ch);
continue;
}
if (!stack.isEmpty())
{
int size = stack.size() - 1;
boolean flag = false;
while (size >= 0 && ch == ')' && stack.get(size) != '(')
{
queue.add(String.valueOf(stack.remove(size)));
size--;
flag = true;
}
if(ch==')'&&stack.get(size) == '(')
{
flag = true;
}
while (size >= 0 && !flag && basic.get(stack.get(size)) >= basic.get(ch))
{
queue.add(String.valueOf(stack.remove(size)));
size--;
}
}
if(ch != ')')
{
stack.add(ch);
}
else
{
stack.remove(stack.size() - 1);
}
}
if(i == charArr.length - 1)
{
if(len > 0)
{
queue.add(String.valueOf(Arrays.copyOfRange(charArr, i - len+1, i+1)));
}
int size = stack.size() - 1;
while (size >= 0)
{
queue.add(String.valueOf(stack.remove(size)));
size--;
}
}
}
String a = queue.toString();
return a.substring(1,a.length()-1);
}
public String dealEquation(String equation){
String [] arr = equation.split(", ");
List<String> list = new ArrayList<String>();
for (int i = 0; i < arr.length; i++)
{
int size = list.size();
switch (arr[i])
{
case "+": double a = Double.parseDouble(list.remove(size-2))+ Double.parseDouble(list.remove(size-2)); list.add(String.valueOf(a)); break;
case "-": double b = Double.parseDouble(list.remove(size-2))- Double.parseDouble(list.remove(size-2)); list.add(String.valueOf(b)); break;
case "*": double c = Double.parseDouble(list.remove(size-2))* Double.parseDouble(list.remove(size-2)); list.add(String.valueOf(c)); break;
case "/": double d = Double.parseDouble(list.remove(size-2))/ Double.parseDouble(list.remove(size-2)); list.add(String.valueOf(d)); break;
default: list.add(arr[i]); break;
}
}
return list.size() == 1 ? list.get(0) : "运算失败" ;
}
}
3.学习使用ListView
MainActivity.java
import android.app.Activity;
import android.os.Bundle;
import android.widget.AdapterView;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.EditText;
import android.widget.Button;
import android.widget.PopupMenu;
import android.view.MenuItem;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button bt1=(Button)findViewById(R.id.bt1);
final ListView lv1=(ListView)findViewById(R.id.lv1);
List<String> list=new ArrayList<String>();
list.add("班级"+" "+"学号"+" "+"姓名");
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,list);
lv1.setAdapter(adapter);
bt1.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v)
{
EditText et_c,et_a,et_n;
et_c=(EditText)findViewById(R.id.et_c);
et_a=(EditText)findViewById(R.id.et_a);
et_n=(EditText)findViewById(R.id.et_n);
ArrayAdapter temp_adp=(ArrayAdapter) lv1.getAdapter();
temp_adp.add(et_c.getText().toString()+" "+et_a.getText().toString()+" "+et_n.getText().toString());
}
});
lv1.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener(){
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
if (id > 0)
{
PopupMenu popup = new PopupMenu(MainActivity.this, view);
popup.getMenuInflater().inflate(R.menu.simple_menu1, popup.getMenu());
popup.show();
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu1:
ArrayAdapter temp_adp = (ArrayAdapter) lv1.getAdapter();
temp_adp.remove(temp_adp.getItem(position));
return true;
default:
return false;
}
}
});
}
return true;
}
});
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.administrator.listviewexp.MainActivity">
<LinearLayout
android:layout_width="370dp"
android:layout_height="200dp"
android:layout_marginBottom="8dp"
android:orientation="vertical"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="0dp">
<LinearLayout
android:layout_width="370dp"
android:layout_height="50dp"
android:orientation="horizontal">
<TextView
android:layout_width="50dp"
android:layout_height="29dp"
android:text="班级:" />
<EditText
android:id="@+id/et_c"
android:layout_width="150dp"
android:layout_height="40dp" />
</LinearLayout>
<LinearLayout
android:layout_width="370dp"
android:layout_height="50dp"
android:orientation="horizontal">
<TextView
android:layout_width="50dp"
android:layout_height="29dp"
android:text="学号:" />
<EditText
android:id="@+id/et_a"
android:layout_width="150dp"
android:layout_height="40dp" />
</LinearLayout>
<LinearLayout
android:layout_width="370dp"
android:layout_height="50dp"
android:orientation="horizontal">
<TextView
android:layout_width="50dp"
android:layout_height="29dp"
android:text="姓名:" />
<EditText
android:id="@+id/et_n"
android:layout_width="150dp"
android:layout_height="40dp" />
</LinearLayout>
<Button
android:id="@+id/bt1"
android:layout_width="80dp"
android:layout_height="40dp"
android:text="添加" /></LinearLayout>
<ListView
android:id="@+id/lv1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:longClickable="true">
</ListView>
</LinearLayout>
simple_main1.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/menu1"
android:orderInCategory="100"
android:title="删除"></item>
<item
android:title="复制"></item>
</menu>
4.组件通信
MainActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.app.Activity;
import android.net.Uri;
import android.view.View.OnClickListener;
public class MainActivity extends Activity {
private static final int SUBACTIVITY1 = 1;
TextView textView;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView)findViewById(R.id.show);
final Button btn1 = (Button)findViewById(R.id.bt1);
btn1.setOnClickListener(new OnClickListener()
{
public void onClick(View view)
{
Intent intent = new Intent(MainActivity.this, SubActivity.class);
startActivityForResult(intent, SUBACTIVITY1);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode)
{
case SUBACTIVITY1:
if (resultCode == RESULT_OK)
{
Uri uriData = data.getData();
textView.setText(uriData.toString());
}
break;
}
}
}
SubActivity.java
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class SubActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.subactivity);
final EditText name = (EditText)findViewById(R.id.name);
final EditText psd = (EditText)findViewById(R.id.psd);
Button btnOK = (Button)findViewById(R.id.btnOK);
btnOK.setOnClickListener(new OnClickListener(){
public void onClick(View view){
String uriString = "用户名:"+name.getText().toString()+" 密码:"+psd.getText().toString();
Uri data = Uri.parse(uriString);
Intent result = new Intent(null, data);
setResult(RESULT_OK, result);
finish();
}
});
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.humphreylin.exp4.MainActivity">
<Button
android:layout_width="100dp"
android:layout_height="50dp"
android:id="@+id/bt1"
android:text="登陆"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.242" />
<TextView
android:layout_width="268dp"
android:layout_height="142dp"
android:id="@+id/show"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:layout_editor_absoluteY="141dp"
tools:layout_editor_absoluteX="37dp"
app:layout_constraintVertical_bias="0.503"
app:layout_constraintHorizontal_bias="0.503" />
</android.support.constraint.ConstraintLayout>
subactivity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.humphreylin.exp4.SubActivity">
<LinearLayout
android:layout_width="370dp"
android:layout_height="300dp"
android:layout_marginBottom="8dp"
android:orientation="vertical"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="0dp">
<LinearLayout
android:layout_width="370dp"
android:layout_height="60dp"
android:orientation="horizontal">
<TextView
android:id="@+id/textView"
android:layout_width="100dp"
android:layout_height="50dp"
android:text="用户名:"
android:textSize="25sp" />
<EditText
android:id="@+id/name"
android:layout_width="150dp"
android:layout_height="50dp" />
</LinearLayout>
<LinearLayout
android:layout_width="370dp"
android:layout_height="60dp"
android:orientation="horizontal">
<TextView
android:layout_width="100dp"
android:layout_height="50dp"
android:text="密码:"
android:textSize="25sp"/>
<EditText
android:id="@+id/psd"
android:layout_width="150dp"
android:layout_height="50dp" />
</LinearLayout>
<Button
android:id="@+id/btnOK"
android:layout_width="150dp"
android:layout_height="75dp"
android:text="登陆"
android:textSize="25sp"/>
</LinearLayout>
</LinearLayout>
androidmanifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.humphreylin.exp4" >
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme" >
<activity android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:label="@string/app_name" android:name=".SubActivity"> </activity>
</application>
</manifest>
5.使用线程
MainActivity.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity{
private static Handler handle = new Handler();
private static TextView textview = null;
private static String str1;
public static void UpdateGUI(String string){
str1 = string;
handle.post(RefreshLable);
}
private static Runnable RefreshLable=new Runnable(){
@Override
public void run(){
textview.setText(str1);
}
};
@Override
public void onCreate(Bundle onSaveInstanceState){
super.onCreate(onSaveInstanceState);
setContentView(R.layout.activity_main);
final TextView textview = (TextView)findViewById(R.id.show);
final Button resetButton=(Button)findViewById(R.id.reset);
final Button beginButton=(Button)findViewById(R.id.start);
final Button stopButton=(Button)findViewById(R.id.stop);
final Intent serviceIntent=new Intent(this,produce.class);
resetButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view){
textview.setText(00+":"+00+":"+000);
}
});
beginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startService(serviceIntent);
}
});
stopButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
stopService(serviceIntent);
}
});
}
}
produce.java
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import java.util.Calendar;
public class produce extends Service{
private Thread thread;
private int mi0,s0,ms0;
@Override
public void onCreate(){
super.onCreate();
thread=new Thread(null,backgroundThread,"thread");
}
@Override
public void onStart(Intent intent,int startId){
super.onStart(intent,startId);
if(!thread.isAlive()){
thread.start();
Calendar cal=Calendar.getInstance();
mi0=cal.get(Calendar.MINUTE);
s0=cal.get(Calendar.SECOND);
ms0=cal.get(Calendar.MILLISECOND);
}
}
@Override
public void onDestroy(){
super.onDestroy();
thread.interrupt();
}
@Override
public IBinder onBind(Intent intent){
return null;
}
private Runnable backgroundThread=new Runnable() {
@Override
public void run() {
try{
while(!Thread.interrupted()){
Calendar cal=Calendar.getInstance();
int mi=Math.abs(cal.get(Calendar.MINUTE)-mi0);
int s=Math.abs(cal.get(Calendar.SECOND)-s0);
int ms=Math.abs(cal.get(Calendar.MILLISECOND)-ms0);
String str=mi+":"+s+":"+ms;
MainActivity.UpdateGUI(str);
Thread.sleep(0);
}
}catch(InterruptedException e){
e.printStackTrace();
}
}
};
}
androidmanifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.humphreylin.exp51">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".produce"/>
</application>
</manifest>
6.数据存储和访问
MainActivity.java
import android.app.Activity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupMenu;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity {
private DBAdapter dbAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button btnAdd = (Button) findViewById(R.id.btnAdd);
final ListView lv1 = (ListView) findViewById(R.id.lv1);
final EditText addClassEditText = (EditText) findViewById(R.id.addClass);
final EditText addSnoEditText = (EditText) findViewById(R.id.addSno);
final EditText addSnameEditText = (EditText) findViewById(R.id.addSname);
dbAdapter = new DBAdapter(this);
dbAdapter.open();
List<String> list = new ArrayList<String>();
list.add("ID" + " " + "班级" + " " + "学号" + " " + "姓名");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
lv1.setAdapter(adapter);
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Student ss = new Student();
String sno = addSnoEditText.getText().toString();
String sname = addSnameEditText.getText().toString();
String classes = addClassEditText.getText().toString();
ArrayAdapter temp_adp = (ArrayAdapter) lv1.getAdapter();
temp_adp.add(dbAdapter.insert(ss) + " " + classes + " " + sno + " " + sname);
}
});
lv1.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
if (id > 0) {
PopupMenu popup = new PopupMenu(MainActivity.this, view);
popup.getMenuInflater().inflate(R.menu.main, popup.getMenu());
popup.show();
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu1:
ArrayAdapter temp_adp = (ArrayAdapter) lv1.getAdapter();
temp_adp.remove(temp_adp.getItem(position));
return true;
default:
return false;
}
}
});
}
return true;
}
});
}
}
DBAdapter.java
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class DBAdapter {
private final Context context;
private SQLiteDatabase db;
private DBHelper dbHelper;
private final static String DB_TABLE="studentinfo";
private final static String DB_NAME="student.db";
private final static int DB_VERSION=1;
private final static String KEY_ID="id";
private final static String KEY_SNO="sno";
private final static String KEY_SNAME="sname";
private final static String KEY_CLASSES="classes";
public DBAdapter(Context _cContext) {
context = _cContext;
}
public void close()
{
if(db!=null)
{
db.close();
db=null;
}
}
public void open() throws SQLiteException
{
dbHelper = new DBHelper(context, DB_NAME, null, DB_VERSION);
try
{
db = dbHelper.getWritableDatabase();
}
catch(Exception e)
{
db = dbHelper.getReadableDatabase();
}
}
public long insert(Student s)
{
ContentValues cv = new ContentValues();
cv.put(KEY_SNO,s.getSno() );
cv.put(KEY_SNAME, s.getSname());
cv.put(KEY_CLASSES, s.getClasses());
return db.insert(DB_TABLE, null, cv);
}
public Student[] convertToStudent(Cursor c)
{
int resultsCount = c.getCount();
if(resultsCount==0||!c.moveToFirst())
{
return null;
}
Student []stu = new Student[resultsCount];
for (int i = 0; i < stu.length; i++) {
stu[i] = new Student();
String sno = c.getString(c.getColumnIndex("sno"));
String sname = c.getString(c.getColumnIndex("sname"));
String classes = c.getString(c.getColumnIndex("classes"));
stu[i].id=c.getInt(0);
stu[i].setSno(sno);
stu[i].setSname(sname);
stu[i].setClasses(classes);
c.moveToNext();
}
return stu;
}
private static class DBHelper extends SQLiteOpenHelper{
public DBHelper(Context context, String name, CursorFactory factory, int version) {
super(context, name, factory, version);
}
private static final String SQL="CREATE TABLE studentinfo ("
+ "id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "sno TEXT DEFAULT NONE,"
+ "sname TEXT DEFAULT NONE,"
+ "classes TEXT DEFAULT NONE"
+ ")";
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(SQL);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS"+DB_TABLE);
onCreate(db);
}
}
}
Student.java
import java.io.Serializable;
public class Student implements Serializable{
public int id=-1;
public String sno;
public String sname;
public String classes;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getSno() {
return sno;
}
public void setSno(String sno) {
this.sno = sno;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getClasses() {
return classes;
}
public void setClasses(String classes) {
this.classes = classes;
}
@Override
public String toString() {
return "id:" + id +" " + "学号:" + sno +" "+ "姓名:" + sname +" "+ "班级:" + classes ;
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.administrator.exp6.MainActivity"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TableRow
android:id="@+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/viewSno"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="学号:"
android:textSize="20dp"/>
<EditText
android:id="@+id/addSno"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
</TableRow>
<TableRow
android:id="@+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/viewSname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="姓名:"
android:textSize="20dp"/>
<EditText
android:id="@+id/addSname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10" />
</TableRow>
<TableRow
android:id="@+id/tableRow3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/viewClass"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="班级:"
android:textSize="20dp"/>
<EditText
android:id="@+id/addClass"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10" />
</TableRow>
<LinearLayout
android:layout_height="wrap_content"
android:gravity="center">
<Button
android:id="@+id/btnAdd"
android:layout_width="150px"
android:layout_height="wrap_content"
android:textSize="35px"
android:text="添加" />
</LinearLayout>
</TableLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ListView
android:id="@+id/lv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
</LinearLayout>
</LinearLayout>