文章目录
- Android Studio
-
- 1、自己建立的小[demo](\压力示功计项目)
-
- 1.1 登录界面
- 1.2 获取系统时间
- 1.3 简单的退出弹窗
- 1.4 随时退出程序,不返回上一个界面
- 1.5 返回键退出
- 1.6 下拉选项
- 1.7 SharedPreferences 存储
- 1.8 文件存储
- 1.9 radiogroup
- 1.10 从应用进入文件按管理器,选中文件得到路径
- 1.11 [安卓打开已近存储的数据并显示](https://blog.csdn.net/qq_44752278/article/details/107079067)
- 1.12 把每个Activity上面的标题去掉
- demo下载
Android Studio
在这几个月的项目过程中,无论是单片机还是java都是从无到有。在网上查找了好多资料,几乎每一个功能的在AS上实现都需要用一个小demo去测试下好不好用再移植到项目中去。项目也比较简单,但对于我这种刚开始接触程序的人来说。有点麻烦。请多指教。那么就从登陆界面开始吧。
1、自己建立的小demo
1.1 登录界面
在EditTextActivity中
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ddgJTyJ3-1594549843633)(${学习文档-Typora各类图片存储地点}/1594542962645.png)]
布局代码
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="15dp"
android:orientation="vertical">
<EditText
android:id="@+id/et_phone"
android:layout_width="match_parent"
android:layout_height="50dp"
android:textSize="16sp"
android:textColor="#000000"
android:background="@drawable/bg_username"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:layout_marginTop="40dp"
android:hint="用户名/手机号"
android:maxLines="1"
android:drawableLeft="@drawable/icon_user1"
android:drawablePadding="5dp"
/>//inputType="number" 数字键盘
// android:background="@drawable/bg_username"在Drawable中的定义圆角和颜色
//要在输入框内部加入小图标,得现在Drawable中添加图片,
//并且图片会随着分辨率的改变而自动变化.
<EditText
android:id="@+id/et_password"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_below="@id/et_phone"
android:layout_marginTop="40dp"
android:textSize="16sp"
android:textColor="#000000"
android:background="@drawable/bg_username"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:hint="密码"
android:inputType="textPassword"
android:drawableLeft="@drawable/icon_password"
android:drawablePadding="5dp"
/>//inputType="textPassword 把显示的密码变成*不可见形式
//ddrawable/icon_password是图标,drawable/bg_username是.xml
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/cb_remember_pass"
android:text="记住账号密码"
android:layout_below="@+id/et_password"/>
<Button
android:layout_width="match_parent"
android:layout_height="40dp"
android:id="@+id/login"
android:layout_below="@id/et_password"
android:layout_marginTop="40dp"
android:background="@drawable/bg_btn3"
android:text="登录"
android:textSize="20sp"
android:textColor="#FFFFFF"
android:gravity="center"/>
//android:gravity="center"文本居中
//设置toast效果,
</RelativeLayout>
实现代码
public class EditTextActivity extends AppCompatActivity {
private Button mLogin;
private EditText mEtPhone;
private EditText mEtPassword; //声明按钮的名称
private CheckBox mCbRememberPass;
private String TAG = "EditTextActivity";
private SharedPreferences.Editor mEditor;
private String SP_Phone = "sp_phone";
private String SP_PASSWD = "sp_passwd";
private String SP_REMEMBER = "sp_remember";
private boolean mIsChecked = true;//声明一开始勾选框处于的状态
private SharedPreferences mSharedPreferences;//SharedPreferences声明空间
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_text);
//初始化控件
initUI();
//初始化数据
initData();
//第一次进入,只要有输入就会在SharedPreferences建立config文件
mCbRememberPass.setChecked(mIsChecked);//第一次登陆剧设置勾选框位点击状态,这样在文本改变之后就会监听
//否则,会在第一次装软件的时候,刚进入,即使密码正确,也登陆不上。应为一开始,没有点击的话,
//在SharedPreferences是没有数据保存的,这样,下面的IF语句执行不下去。无法进入。
setEditTextInputSpeChat(mEtPhone);//使其无法输入一些特殊字符
/**
* 登录操作,密码设定写死
* */
mLogin = findViewById(R.id.login);
mLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(mEtPhone.getText().toString().equals("123")&&mEtPassword.getText().toString().equals("123")){
//判断mEtPassword与mEtPhone得到文本存储的字符串是否等于 123
Intent intent = new Intent(EditTextActivity.this, TestActivity.class);
startActivity(intent);
Toast.makeText(getApplicationContext(), "登录成功",
Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "账号或密码不正确",
Toast.LENGTH_LONG).show();
}
}
});
}
private void initData() {
//实例化SharedPreferences
if(mSharedPreferences ==null){
mSharedPreferences = getApplicationContext().getSharedPreferences("config", Context.MODE_PRIVATE);
}
//回显示数据
//设置 在mSharedPreferences保存的字符串,名字是SP_Phone
mEtPhone.setText(mSharedPreferences.getString(SP_Phone,""));
//设置 在mSharedPreferences保存的字符串,名字是SP_PASSWD
mEtPassword.setText(mSharedPreferences.getString(SP_PASSWD,""));
//要得到mIsChecked状态
mIsChecked = mSharedPreferences.getBoolean(SP_REMEMBER,false);
//设置勾选按钮的状态
mCbRememberPass.setChecked(mIsChecked);
}
private void initUI() {
//获取电话和密码输入框
mEtPhone = findViewById(R.id.et_phone);
//文本改变后,监听者对象
mEtPhone.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
//文本改变之后,记录用户账户
if(mIsChecked){//如果处于勾选状态的话,才会监听
if(mSharedPreferences ==null){
mSharedPreferences = getApplicationContext().getSharedPreferences("config", Context.MODE_PRIVATE);
}
//实例化SharedPreferences的编辑者对象
mEditor = mSharedPreferences.edit();
//存储账号
mEditor.putString(SP_Phone,mEtPhone.getText().toString());//把得到的数组put进入Text
//提交
mEditor.commit();
}
}
});
mEtPassword = findViewById(R.id.et_password);
//文本改变后,监听者对象
mEtPassword.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {//文本改变之后,记录用户密码
if(mIsChecked){//如果勾选是true
if(mSharedPreferences ==null){
mSharedPreferences = getApplicationContext().getSharedPreferences("config", Context.MODE_PRIVATE);
}
//实例化SharedPreferences的编辑者对象
mEditor = mSharedPreferences.edit();
//存储密码
mEditor.putString(SP_PASSWD,mEtPassword.getText().toString());
mEditor.commit();
}
if(mIsChecked == false){
mSharedPreferences.edit().clear().commit();
}
}
});
//获取勾选按钮
mCbRememberPass = findViewById(R.id.cb_remember_pass);
mCbRememberPass.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.d(TAG,"状态为"+isChecked);//设置日志,方便观察,当选中,则会显示状态为true
mIsChecked = isChecked;
if(isChecked){
//实例化SharedPreferences对象
if(mSharedPreferences == null){
mSharedPreferences = getApplicationContext().getSharedPreferences("config", Context.MODE_PRIVATE);
}
//实例化SharedPreferences的编辑者对象
mEditor = mSharedPreferences.edit();
// mSharedPreferences = getApplicationContext().getSharedPreferences("config", Context.MODE_PRIVATE);
// //实例化SharedPreferences的编辑者对象
// mEditor = mSharedPreferences.edit();
//存储数据
mEditor.putString(SP_Phone,mEtPhone.getText().toString());//把得到的数组put进入Text
mEditor.putString(SP_PASSWD,mEtPassword.getText().toString());
mEditor.putBoolean(SP_REMEMBER ,isChecked);//点击的状态给put
//提交
mEditor.commit();
}else {//修改过::如果记住密码位false,则清空缓存空间。
//这有个问题,清空的话那么会把SharedPreferences清掉,其他数据也会清理掉。后来想了想,可以给其值赋值为空
// mSharedPreferences.edit().clear().commit();//则清空缓存空间。
mEditor.clear().commit();//清空mEditor
}
}
});
}
public static void setEditTextInputSpeChat(EditText editText) {//使其无法输入一些特殊字符
InputFilter filter = new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
String speChat = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]";
Pattern pattern = Pattern.compile(speChat);
Matcher matcher = pattern.matcher(source.toString());
if (matcher.find()) {
return "";
} else {
return null;
}
}
};
editText.setFilters(new InputFilter[]{filter});
}
Toast事件
// public void showToast(View view) {//按钮被按后弹出信息—被点击了
// Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show();
// }
}
1.2 获取系统时间
/**
* 获取时间
*/
@SuppressLint("SimpleDateFormat")
SimpleDateFormat formatter = new SimpleDateFormat ("HH时mm分ss秒");
SimpleDateFormat formatter2 = new SimpleDateFormat ("HH:mm:ss");
Date curDate = new Date(System.currentTimeMillis());
TextView mtv_quit_show_1 = findViewById(R.id.tv_quit_show_1);//控件
//获取当前时间
String str = formatter.format(curDate);
String str2 = formatter2.format(curDate);
mtv_quit_show_1.setText(str+"--"+str2);//显示
1.3 简单的退出弹窗
/**
* 简单退出弹窗事件
*/
mtv_quit_show =findViewById(R.id.tv_quit_show);
Button button_quit=(Button)findViewById(R.id.btn_Quit);
//为"退出"按钮添加单击事件监听器
button_quit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AlertDialog alert=new AlertDialog.Builder(TextViewActivity.this).create();
// alert.setIcon(R.drawable.stop);//设置图标
alert.setTitle("退出?");
alert.setMessage("真的要退出本软件吗?");
//添加取消按钮
alert.setButton(DialogInterface.BUTTON_NEGATIVE,"取消",new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
//添加"确定"按钮
alert.setButton(DialogInterface.BUTTON_POSITIVE,"是的", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
finish();//退出这个界面
}
});
alert.show();
}
});
1.4 随时退出程序,不返回上一个界面
在做很多个界面来回切换的时候,点击返回键会返回到上一个界面去。有时我们需要上一个界面还是运行的状态,但是,有时候我们想的是直接退出,会连续按好几个返回键才退出。
首先创建一个ActivityCollector.class文件
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-IPwUygYn-1594549843636)(${学习文档-Typora各类图片存储地点}/1594544012688.png)]
/**
* 在活动管理器中,通过一个LIST存活动,进行活动的添加、移除和销毁
*
*/
public class ActivityCollector {
public static List<Activity> activities = new ArrayList<>();
public static void addActivity(Activity activity) {//活动的添加
activities.add(activity);
}
public static void removeActivity(Activity activity) {//活动的移除
activities.remove(activity);
}
public static void finishAll() {//活动的销毁
for (Activity activity : activities) {
if (!activity.isFinishing()) {
activity.finish();
}
}
}
}
然后我们在你的起始界面(我的是main.activity)onCreate(主程序)中添加
ActivityCollector.addActivity(this);//添加活动管理器,方便在必要时候直接退出程序。
// 而不是频繁的返回上一个界面
接着还是在这个界面重写onDestroy()方法,onCreate之外写
/**
* 重写onDestroy方法
*/
//在主启动界面程序中重写onDestroy方法,我会在ButtonActivity下写,结合弹窗界面
@Override
protected void onDestroy() {
super.onDestroy();
ActivityCollector.removeActivity(this);
}
之后在每个Acitivity中添加
1.5 返回键退出
/**
*
* @param //重写keyCode方法
* @param //防止自己写的应用程序不小心点击退出键而直接退出,在按下安卓自带的返回键后会提示
* @return
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK )
{
// 创建退出对话框
AlertDialog isExit = new AlertDialog.Builder(this).create();
// 设置对话框标题
isExit.setTitle("系统提示");
// 设置对话框消息
isExit.setMessage("确定要退出吗");
// 添加选择按钮并注册监听
isExit.setButton("确定", listener);
isExit.setButton2("取消", listener);
// 显示对话框
isExit.show();
}
return false;
}
/**监听对话框里面的button点击事件*/
DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
switch (which)
{
case AlertDialog.BUTTON_POSITIVE:// "确认"按钮退出程序
ActivityCollector.finishAll();//结束整个程序
android.os.Process.killProcess(android.os.Process.myPid());//杀死当前进程代码
break;
case AlertDialog.BUTTON_NEGATIVE:// "取消"第二个按钮取消对话框
break;
default:
break;
}
}
};
1.6 下拉选项
定义一个spinner
<Spinner
android:id="@+id/spinner1"
android:layout_marginTop="300dp"
android:layout_width="match_parent"
android:layout_height="60dp"
android:spinnerMode="dialog"
android:background="@drawable/bg_btn2"
android:theme="@style/itemSpinnerStyle"/>
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="textview" />
实现
private List<String> list = new ArrayList<String>();
private ArrayAdapter<String> adapter;
//第一步:定义下拉列表内容
list.add("A型");
list.add("B型");
list.add("O型");
list.add("AB型");
list.add("其他");
textview = findViewById(R.id.textView1);
spinnertext = findViewById(R.id.spinner1);
//第二步:为下拉列表定义一个适配器
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
//第三步:设置下拉列表下拉时的菜单样式
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//第四步:将适配器添加到下拉列表上
spinnertext.setAdapter(adapter);
//第五步:添加监听器,为下拉列表设置事件的响应
spinnertext.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
/* 将所选spinnertext的值带入myTextView中*/
textview.setText("你的血型是:" + adapter.getItem(position));
/* 将 spinnertext 显示^*/
parent.setVisibility(View.VISIBLE);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
textview.setText("NONE");
parent.setVisibility(View.VISIBLE);
}
});
// //将spinnertext添加到OnTouchListener对内容选项触屏事件处理
// spinnertext.setOnTouchListener(new Spinner.OnTouchListener() {
// @Override
// public boolean onTouch(View v, MotionEvent event) {
// // TODO Auto-generated method stub
// // 将mySpinner隐藏,即点开下拉,没点击选项,而是点击屏幕上的地方,会把整个Spinner隐藏
// v.setVisibility(View.INVISIBLE);
// Log.i("spinner", "Spinner Touch事件被触发!");
// return false;
// }
// });
//焦点改变事件处理
spinnertext.setOnFocusChangeListener(new Spinner.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
v.setVisibility(View.VISIBLE);
Log.i("spinner", "Spinner FocusChange事件被触发!");
}
});
1.7 SharedPreferences 存储
布局
<EditText
android:id="@+id/et_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="输入内容"/>
<Button
android:id="@+id/btn_save"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="保存"/>
<Button
android:id="@+id/btn_show"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="显示"/>
<TextView
android:id="@+id/tv_showcontent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
/>
实现
private EditText mEtName;
private Button mBtnSave,mBtnShow;
private TextView mTvShowContent;
private SharedPreferences mSharedPreferences;//SharedPreferences声明空间
private SharedPreferences.Editor mEditor;
mEtName = this.<EditText>findViewById(R.id.et_name);
mBtnSave = this.<Button>findViewById(R.id.btn_save);
mBtnShow = this.<Button>findViewById(R.id.btn_show);
mTvShowContent = this.<TextView>findViewById(R.id.tv_showcontent);
//获取SharedPreferences实例
mSharedPreferences = getSharedPreferences("date",MODE_PRIVATE);//文件名+模式
//获取编辑者对象
mEditor = mSharedPreferences.edit();
mBtnSave.setOnClickListener(new View.OnClickListener() {//点击事件
@Override
public void onClick(View v) {//通过haredPreferences保存起来
mEditor.putString("name",mEtName.getText().toString());// name后面就是获取et_name对应EditText里面的内容
mEditor.apply();//提交使put上去内容生效,存储完了。
}
});
mBtnShow.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mTvShowContent.setText(mSharedPreferences.getString("name",""));
}
});
1.8 文件存储
会显示在根目录下面,这里面要在mainfest.xml中加权限才能直接操作根目录下面的文件创建。且最近安卓10发布后,要禁止在根目录下建文件夹了。
布局
<EditText
android:id="@+id/et_dir_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="文件夹名"/>
<EditText
android:id="@+id/et_dir_name_2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="2级文件夹名"/>
<EditText
android:id="@+id/et_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="输入内容"/>
<Button
android:id="@+id/btn_save"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="保存"/>
<Button
android:id="@+id/btn_show"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="显示"/>
<TextView
android:id="@+id/tv_showcontent"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginTop="10dp"
/>
<TextView
android:id="@+id/tv_2"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginTop="10dp"
/>
实现
private EditText mEtName, mEtDirName, mEtDirName2;
private Button mBtnSave, mBtnShow;
private TextView mTvShowContent, mtv_2;
private final String mFileName = "test.txt";
private String T, T1;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_file);
mEtName = this.<EditText>findViewById(R.id.et_name);
mBtnSave = this.<Button>findViewById(R.id.btn_save);
mBtnShow = this.<Button>findViewById(R.id.btn_show);
mTvShowContent = this.<TextView>findViewById(R.id.tv_showcontent);
mEtDirName = findViewById(R.id.et_dir_name);
mtv_2 = findViewById(R.id.tv_2);
mEtDirName2 = findViewById(R.id.et_dir_name_2);
mBtnSave.setOnClickListener(new View.OnClickListener() {//点击保存,调用sava方法
@Override
public void onClick(View v) {
T = mEtDirName.getText().toString();
T1 = mEtDirName2.getText().toString();
mtv_2.setText(T);
save(mEtName.getText().toString());//点击保存把text内容给tostring,
}
});
mBtnShow.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mTvShowContent.setText(read());
}
});
}
//存储数据//一级文件夹的
private void save1(String content){
//通过FileOutputStream 实现存数据
FileOutputStream fileOutputStream = null;//声明,如果不在外面声明,也可以执行被注销的那段,这段要删去
try {
//创建文件夹
File dir =new File(Environment.getExternalStorageDirectory(),T);//定义了文件夹的名称
if(!dir.exists()){
dir.mkdir();
Log.d("tets1", "save: 1创建文件1夹成功");
}
//创建文件,文件名称=T+mFileName
File file = new File(dir,T+mFileName);//XX+test.txt,注意必须要有.txt后缀才是能打开的txt文本文件
if (!file.exists()){
file.createNewFile();
Log.d("tets1", "save:2 创建文件成功");
}
fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(content.getBytes());//传一个字节数组,写入数据
} catch (IOException e) {
e.printStackTrace();
}finally {//finally无论如何最后都要执行这一段,如果不写这段,写上面注销三段代码也行。
if(fileOutputStream != null){//用if语句是为了防止它为空指针时候,造成异常。
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//读取数据
private String read() {
FileInputStream fileInputStream = null;
try {
// fileInputStream = openFileInput(mFileName);读取的
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + T + File.separator + T1, T + mFileName);
fileInputStream = new FileInputStream(file);
byte[] buff = new byte[1024];
StringBuilder sb = new StringBuilder("");//字符串拼接
int len = 0;
while ((len = fileInputStream.read(buff)) > 0) {
sb.append(new String(buff, 0, len));//字符串的拼接
}
return sb.toString();//返回
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
//存储数据//带有二级文件夹的
private void save(String content) {
FileOutputStream fileOutputStream = null;//声明,如果不在外面声明,也可以执行被注销的那段,这段要删去
try {
//两个参数,文件名和模式
//fileOutputStream = openFileOutput(mFileName,MODE_PRIVATE);//外部定义了private final String mFileName = "test.txt";所以内部test.txt换成FileName
//创建文件夹
File dir = new File(Environment.getExternalStorageDirectory(), T + File.separator + T1);//定义了文件夹的名称
if (!dir.exists()) {
dir.mkdirs();
Log.d("tets1", "save: 1创建文件1夹成功");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
在AndroidMainfest.xml中添加权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
1.9 radiogroup
布局
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:checkedButton="@id/b3"
android:id="@+id/RG">
<!--默认选中b1-->
<RadioButton
android:text="11"
android:id="@+id/b1"
android:layout_height="40dp"
android:layout_width="match_parent"/>
<RadioButton
android:text="22"
android:id="@+id/b2"
android:layout_height="40dp"
android:layout_width="match_parent"
/>
<RadioButton
android:id="@+id/b3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="33" />
</RadioGroup>
<TextView
android:id="@+id/tv_show"
android:layout_width="match_parent"
android:layout_height="40dp"
android:background="#FFEB3B" />
实现
private RadioGroup rg;
private RadioButton b1;
private RadioButton b2;
private RadioButton b3;
private TextView mtvShow;
rg=(RadioGroup)findViewById(R.id.RG);
b1=(RadioButton)findViewById(R.id.b1);
b2=(RadioButton)findViewById(R.id.b2);
b3=(RadioButton)findViewById(R.id.b3);
mtvShow =findViewById(R.id.tv_show);
/**
* RadioGroup 被选中事件
*/
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if(b1.isChecked()){//两种方法 checkedId==b2.getId() //
Toast.makeText(RadioGroupActivity.this,"b1选中", Toast.LENGTH_LONG).show();
}
if(b2.isChecked()){
Toast.makeText(RadioGroupActivity.this,"b2选中", Toast.LENGTH_LONG).show();
}
if(b3.isChecked()){
Toast.makeText(RadioGroupActivity.this,"b3选中", Toast.LENGTH_LONG).show();
}
}
});
mtvShow.setText(b2.getId());//第二种
1.10 从应用进入文件按管理器,选中文件得到路径
注意的是,文件名不能有 “:”存在,否则 会打开不了完整的路径(实测)。
布局
<Button
android:id="@+id/btn_jump_File"
android:layout_width="match_parent"
android:layout_height="70dp"
android:layout_marginTop="20dp"/>
<TextView
android:id="@+id/tv_jump_File"
android:layout_width="match_parent"
android:layout_height="80dp"
android:layout_marginTop="40dp"/>
<TextView
android:id="@+id/tv_jump_File_view"
android:layout_width="match_parent"
android:layout_height="80dp"
android:layout_marginTop="40dp"
android:background="#00F000"/>
实现
private TextView tv;
private TextView tv2;
private Button btn;
private Boolean flage=false;
String path;
String str="";
onCreate()实现
btn = (Button) findViewById(R.id.btn_jump_File);
tv = (TextView) findViewById(R.id.tv_jump_File);
tv2 = (TextView) findViewById(R.id.tv_jump_File_view);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
//intent.setType(“image/*”);//选择图片
//intent.setType(“audio/*”); //选择音频
//intent.setType(“video/*”); //选择视频 (mp4 3gp 是android支持的视频格式)
//intent.setType(“video/*;image/*”);//同时选择视频和图片
// intent.setType("*/*");//无类型限制
intent.setType("txt/*");//没有写异常处理,选择不是项目建的文件夹会报错
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(intent, 1);
}
});
方法实现
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
Uri uri = data.getData();
if ("file".equalsIgnoreCase(uri.getScheme())){//使用第三方应用打开
path = uri.getPath();
tv.setText(path);
tv2.setText(str);
Toast.makeText(this,"11111"+path,Toast.LENGTH_SHORT).show();
return;
}
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {//4.4以后,基本是这个方法,如果得到路径,想继续操作UI的话,可以在这后面实现。我也不太理解怎么再回到上面ONcreat()去执行。
path = getPath(this, uri);
tv.setText(path);
String[] str_split = str.split(",");
tv2.setText(path);
Toast.makeText(this,"222222"+path,Toast.LENGTH_SHORT).show();
} else {//4.4以下下系统调用方法
path = getRealPathFromURI(uri);
tv.setText(path);
tv2.setText(path);
Toast.makeText(FileOpenTestActivity.this, "33333"+path, Toast.LENGTH_SHORT).show();
}
}
}
public String getRealPathFromURI(Uri contentUri) {
String res = null;
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
if(null!=cursor&&cursor.moveToFirst()){;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
res = cursor.getString(column_index);
cursor.close();
}
return res;
}
/**
* 专为Android4.4设计的从Uri获取文件绝对路径,以前的方法已不好使
*/
@SuppressLint("NewApi")
public String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[]{split[1]};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
/**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* @param context The context.
* @param uri The Uri to query.
* @param selection (Optional) Filter used in the query.
* @param selectionArgs (Optional) Selection arguments used in the query.
* @return The value of the _data column, which is typically a file path.
*/
public String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {column};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
final int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is ExternalStorageProvider.
*/
public boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is DownloadsProvider.
*/
public boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is MediaProvider.
*/
public boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
1.11 安卓打开已近存储的数据并显示
1.12 把每个Activity上面的标题去掉
在AndroidMainfest.xml中每个
<activity android:name=".MainActivity"
android:theme="@android:style/Theme.Light.NoTitleBar" >//这句就去掉了标题