安卓学习笔记

TextUtils

//判断字符串不为空
String inputText = ...;
if (!TextUtils.isEmpty(inputText))
    ...

退出应用

@Override
public void onBackPressed() {
    AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(this);
    builder.setTitle("提示");
    builder.setMessage("确定注销吗");
    builder.setNegativeButton("取消", null);
    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            ActivityUtils.getInstance().popAllActivity();
            LoginActivity.actionStart(MainActivity.this);
        }
    });
    builder.show();
}

Intent传值

传值:FirstActivity
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra(key, value); 
startActivity(intent);
接收:SecondActivity
Intent intent = getIntent();
//类型必须一致,这里以Int为例,也可以采用别的类型
intent.getExtras().getInt(key);
//也可以是intent.getIntExtra(key, defaultValue);

Intent回调数据传值

请求:FirstActivity
//当然也可以传值给下一个活动,只是这里没写
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
// 第二个参数是请求码,只要是一个唯一值
startActivityForResult(intent, 1234);
回调:FirstActivity
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        switch (requestCode) {
            case 1234:
                if (resultCode == RESULT_OK) {
                    String returnedData = intent.getStringExtra(key);
                }
                break;
        }
}
传值:SecondActivity
Intent intent = new Intent();
intent.putExtra(key, value);
//专门用于向上一个活动返回数据
//第一个参数用于向上一个活动返回结果码,
//一般只使用RESULT_OK或RESULT_CANCELED这两个值
//第二个参数则是把带有数据的Intent传递回去
setResult(RESULT_OK, intent);
//调用了finish()方法来销毁当前活动
finish();

用Bundle的Intent

Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
Bundle bundle = new Bundle();
bundle.putSerializable(key, value);
//也可以用bundle.putParcelable(key, value);
//bundle也可以传除对象外的数据类型,只是这里用对象为例
//传对象的前提是对象必须序列化
//如用putParcelable,对象必须 implements Parcelable
//如用putSerializable,对象必须 implements Serializable
intent.putExtras(bundle);
startActivity(intent);
//获取数据
intent.getSerializableExtra(key);
intent.getParcelableExtra(key);

//bundle数组,以整形为例
bundle.putIntegerArrayList(key, value);
getIntent().getIntegerArrayListExtra(key);

onCreate的Bundle

使用场景:当一个活动进入停止状态,是有可能被系统回收的,这时重新回到被回收的活动,是不会执行onRestart(),而是执行onCreate(),活动中的临时数据和状态会丢失,怎么办呢?

public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        //5.0后一些特殊行为powered off 或者其他行为
        //他会帮我们保存在outPersistentState中,一种更加坚固的保存数据方式
        super.onSaveInstanceState(outState, outPersistentState);
        outState.putString(key, value);
}

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.id.layout);
        if (savedInstanceState != null) {
            savedInstanceState.getString(value)
        }
}

启动活动的最佳写法

FirstActivity:
SecondActivity.actionStart(FirstActivity.this, data1, data2);
SecondActivity:
public static void actionStart(Context context, String data1, String data2) {
        Intent intent = new Intent(context, SecondActivity.class);
        intent.putExtra(param1, data1);
        intent.putExtra(param2, data2);
        context.startActivity(intent);
}

新建线程

new Thread(new Runnable() {
      @Override
      public void run() {
              //业务逻辑             
      }
}).start();

延时一秒

new Handler().postDelayed(new Runnable() {
        public void run() {
                //业务逻辑             
        }
}, 1000);

Fragment




    

会动的Fragment

//FrameLayout的所有控件默认放在布局的左上角
//非常适合只在布局里放入一个碎片



    

    



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

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button:
                replaceFragment(new RightFragment());
                break;
        }
    }

    private void replaceFragment(Fragment fragment) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.right_layout, fragment);
        //模拟返回栈,接受一个名字描述返回栈的状态,一般传入null即可
        transaction.addToBackStack(null); 
        transaction.commit();
    }

Fragment和activity通信

//获取碎片实例
LeftFragment leftFragment = (LeftFragment) 
getSupportFragmentManager().findFragmentById(R.id.left_fragment);

//获取当前碎片相关联的活动
MainActivity activity = (MainActivity) getActivity();

接受广播

//以监控网络变化为例
//清单文件添加对应权限


private IntentFilter intentFilter;
private NetworkChangeReceiver networkChangeReceiver;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    intentFilter = new IntentFilter();
    intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
    networkChangeReceiver = new NetworkChangeReceiver();
    registerReceiver(networkChangeReceiver, intentFilter);
}

@override
protected void onDestroy() {
    super.onDestroy();
    unregisterReceiver(networkChangeReceiver);
}

class NetworkChangeReceiver extends BroadCastReciver {
    @Override
    public void onReceive(Context context, Intent intent) {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSysytemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getAcitiveNetworkInfo();
        if (networkInfo != null && networkInfo.isAvailable()) {
              Toast.makeText(context, "network is available", Toast.LENGTH_SHORT).show();
        } else {
              Toast.makeText(context, "network is unavailable", Toast.LENGTH_SHORT).show();
        }
    }
}

发送广播

public class MyBroadcastReceiver extends BroadcastReciver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "received in MyBroadcastReceiver", Toast.LENGTH_SHORT).show();
        //有序广播的截断
        //abortBroadcast();
    }
}

//清单文件的application标签中对这个广播接收器进行修改
//静态注册
//enabled 是否启用
//exproted 是否允许这个广播接收器接收本程序以外的广播

        
    
        
    

//发送广播的触发点
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onclick(View v) {
        Intent intent = new Intent("com.example.broadcastter.MY_BROADCAST");
        sendBroadcast(intent);
        //如果是发送有序广播
        //sendOrderedBroadcast(intent, null);
    }
})

使用本地广播

//发送广播
private IntentFilter intFilter;
private LocalReciver localReciver;
private LocalBroadcastManager localBroadcastManager;
//获取实例
localBraodcastManager = LocalBroadcastManager.getInstance(this);
Intent intent = new Intent("com.example.broadcasttest.LOCAL_BROADCAST");
//发送本地广播
localBraodcastManager.sendBroadcast(intent);

@Override
protected void onDestroy() {
    super.onDestroy();
    localBroadcastManager.unregisterReceiver(localReceiver);
}

class LocalReceive extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "received local broadcast", Toast.LENGTH_SHORT).show();
    }
}
//接受广播
Intent intent = new Intent("com.example.broadcasttest.LOCAL_BROADCAST");
localBroadcastManager.sendBroadcast(intent);

将数据存储到文件中

//适合存储一些简单的文本数据或二进制数据
public void() {
    String data = "Data to save";
    FileOutputStream out = null;
    BufferedWriter writer = null;
    try {
        //第一个参数是文件名,文件路径默认为/dada/data//files/
        //MODE_PRIVATE表示文件同名时覆盖
        //MODE_APPEND表示文件同名时添加
        out = openFileOutput("data", Context.MODE_PRIVATE);
        writer = new BufferedWriter(new OutputStreamWriter(out));
        writer.write(data);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (writer != null) 
                writer.close();
        } catch (IOException e) {
             e.printStackTrace();
        }
    }
}

从文件中读取数据

public String load() {
    FileInputStream in = null;
    BufferedReader reader = null;
    StringBuilder context = new StringBuilder();
    try {
        in = openFIleInput("data");
        reader = new BufferedReader(new InputStreamReader(in));
        String line = "";
        while ((line = reader.readLine) != null) {
            content.append(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
             if (reader != null) 
                 reader.close();
        } catch (IOException e) {
             e.printStackTrace();
        }
    }
    return content.toString();
}

获取控件的宽和高

public class MyImageView extends android.support.v7.widget.AppCompatImageView {
    public MyImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    public MyImageView(Context context) {
        super(context);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
    }
}



ViewTreeObserver vto = ivToolbar.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        ivToolbar.getViewTreeObserver().removeOnGlobalLayoutListener(this);
        Log.i("measure", ivToolbar.getWidth() + " , " + ivToolbar.getHeight());
    }
});

参考:http://blog.csdn.net/johnny901114/article/details/7839512

你可能感兴趣的:(安卓学习笔记)