线性布局管理器:LinearLayout
android:orientation="vertical"
android:orientation="horizontal"
android:gravity="center"
android:gravity="right|bottom"
android:layout_weight="1"
基本程序单元:Activity
4种状态:
生命周期:
onRestart()
返回onStart()
)创建、启动和关闭Activity:
(也可以直接右键包通过Android Studio新建Activity)
创建继承自Activity的Activity
public class MainActivity extends Activity{
//...
}
重写需要回掉的方法
public class MainActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
设置要显示的视图
public class MainActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);//设置布局
}
}
在AndroidManifest.xml
的
中配置Activity
<activity android:name="com.yuxiang.MyActivity" android:label="MyActivity">activity>
启动和关闭Activity:
入口Activity:
配置AndroidManifest.xml
,通过Intent来表达自己的“意图”:
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
其他Activity:
通过startActivity()
来启动
关闭Activity:
通过finish()
来关闭
刷新Activity:
通过onCreate(null)
来刷新(如果该类继承的是AppCompatActivity
的话则不能使用,必须是Activity
)
Activity ComponentName:
Intent intent = new Intent();
ComponentName componentName = new ComponentName("com.yuxiang.myapplication","com.yuxiang.myapplication.FileExplore");
intent.setComponent(componentName);
startActivity(intent);
文本框:TextView
android:textSize="27sp"
android:textColor="#FF0000"
android:singleLine="true"
编辑框:EditText
android:layout_width="match_parent"
android:layout_width="wrap_content"
android:hint="请输入名称"
android:inputType="textPassword"
android:inputType="number"
android:background="@null"
android:drawableStart="@mipmap/img"
android:drawableEnd="@mipmap/img"
android:drawableTop="@mipmap/img"
android:drawableBottom="@mipmap/img"
android:drawablePadding="2dp"
android:lines="5"
android:singleLine="true"
getText()
方法xml代码:
android:id="@+id/btn"
Java代码:
Button button = findViewById(R.id.btn);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "Click!", Toast.LENGTH_SHORT).show();
}
});
在strings.xml(位于app
> res
> values
> strings.xml
下)下添加:
<string name="demo">测试string>
xml内的使用方法:
android:text="@string/demo"
请先在AndroidManifest.xml
文件中添加联网权限:
<uses-permission android:name="android.permission.INTERNET"/>
Java代码:
MediaPlayer mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource("url");
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mediaPlayer) {
mediaPlayer.start();
}
});
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.stop();
mediaPlayer.release();
}
});
} catch (IOException e) {
e.printStackTrace();
}
onKeyDown()
onKeyUp()
onKeyLongPress()
物理按键常量:
KeyEvent类的按键名称 | 说明 |
---|---|
KEYCODE_HOME | 主页键(未开发给普通应用) |
KEYCODE_BACK | 返回键 |
KEYCODE_VOLUME_UP | 加大音量键 |
KEYCODE_VOLUME_DOWN | 减小音量键 |
KEYCODE_POWER | 电源键(未开发给普通应用) |
KEYCODE_ENTER | 回车键 |
KEYCODE_DEL | 删除键 |
KEYCODE_MENU | 菜单键 |
KEYCODE_SEARCH | 搜索键 |
KEYCODE_APP_SWITCH | 任务键(未开发给普通应用) |
连续按下两次“返回键”退出应用程序
在Android Studio下按下Alt+Insert选择Override Methods...
(重写方法),然后输入onKeyDown
,回车即可快速插入
public class MainActivity extends Activity {
private long exitTime = 0;
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
exit();
return true;
}
return super.onKeyDown(keyCode, event);
}
private void exit() {
if ((System.currentTimeMillis() - exitTime) > 2000) {
Toast.makeText(MainActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
exitTime = System.currentTimeMillis();
} else {
finish();
System.exit(0);
}
}
}
给EditText添加按键监听
final EditText editText = findViewById(R.id.edit);
final TextView textView = findViewById(R.id.text);
editText.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View view, int i, KeyEvent keyEvent) {
if (keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
switch (i) {
case KeyEvent.KEYCODE_ENTER:
textView.setText("按键为回车键");
break;
case KeyEvent.KEYCODE_DEL:
textView.setText("按键为删除键");
break;
case KeyEvent.KEYCODE_SEARCH:
textView.setText("按键为搜索键");
break;
case KeyEvent.KEYCODE_BACK:
textView.setText("按键为返回键");
break;
case KeyEvent.KEYCODE_MENU:
textView.setText("按键为菜单键");
break;
case KeyEvent.KEYCODE_VOLUME_UP:
textView.setText("按键为音量+键");
break;
case KeyEvent.KEYCODE_VOLUME_DOWN:
textView.setText("按键为音量-键");
break;
}
}
return false;
}
});
监听软键盘点击回车及换行事件
editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEND || actionId == EditorInfo.IME_ACTION_DONE || (event != null && KeyEvent.KEYCODE_ENTER == event.getKeyCode() && KeyEvent.ACTION_DOWN == event.getAction())) {
Toast.makeText(MainActivity.this, "Enter!", Toast.LENGTH_SHORT).show();
}
return false;
}
});
附:屏蔽系统音量键
重写onKeyDown()
方法即可
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
return true;
}
if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
return true;
}
return super.onKeyDown(keyCode, event);
}
在AndroidManifest.xml中配置
添加:
android:configChanges="keyboardHidden|screenSize|orientation"
在你所指定的activity中加上android:screenOrientation
即可,下面是一些参数:
在Java代码中设置
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
假设当前是横屏,会把已经横屏的屏幕旋转180°。
所以我们先要做一个判断,再执行旋转屏幕操作:
if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
新建横屏布局:
res
目录下新建Android Resource Directory
layout
> Orientation
Landscape
设置无标题:
requestWindowFeature(Window.FEATURE_NO_TITLE);
去标题栏更简单的方法:直接继承Activity
类即可
设置全屏:
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
注意:要放在setContentView()
方法前面!
读权限:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
写权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Java代码:
File f = new File("/storage/emulated/0/Download/test.txt");
FileReader fr = null;
BufferedReader br = null;
try {
fr = new FileReader(f);
br = new BufferedReader(fr);
String tmp;
int i = 1;
while ((tmp = br.readLine()) != null) {
System.out.println("D" + i + ":" + tmp);
i++;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fr != null) {
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
字符串分割:str.split(',')
判断字符串是否相等:str.equal("str")
File file = new File("/storage/emulated/0/Download/test.txt");
if (!file.exists()){
Toast.makeText(this, "/storage/emulated/0/Download/test.txt 文件不存在", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "文件存在", Toast.LENGTH_SHORT).show();
}
if (ActivityCompat.checkSelfPermission(this, "android.permission.READ_EXTERNAL_STORAGE") != PackageManager.PERMISSION_GRANTED){
Toast.makeText(this, "没有存储权限", Toast.LENGTH_SHORT).show();
}
编辑gradle.properties
文件,添加:
android.injected.testOnly=false
Random类
语法:
Random r = new Random();
nextInt()
:返回随机int值nextLong()
:返回随机long值nextDouble()
:返回随机double值nextFloat()
:返回随机float值nextBoolean()
:返回随机boolean值范围:
0 <= nextInt(int n) < n
Math.random()
Math.random()
范围:0<=double值<1
同理可得:
实例:获取0-100的随机数Math.random()*m
范围:0<=double值int num = (int)(Math.random()*100);