android入门学习
第三章
TextView
gravity指定文字对齐方式,可以使用|指定多个指
字体大小sp为单位
Button
textAllCaps大小写自动转换
EditText
hint提示文字
maxLines最大行数
获取EditText的输入内容editText.getText().toString()
ImageView
图片一般放在drawable目录下,指定分辨率
src设定图片目录
代码设置imageView.setImageResource(R.drawable.xxxx)
ProgressBar
可见属性android:visibility,可选值:visible可见,invisible不可见但占位,gone不可见不占位
在隐藏和显示之间来回切换
if (progressBar.getVisibility() == View.GONE) {
progressBar.setVisibility(View.VISIBLE);
} else {
progressBar.setVisibility(View.GONE);
}
style属性设定样式,圆形,水平
style="?android:attr/progressBarStyleHorizontal"
max属性设定进度条最大值
动态改变进度条进度
int progress = progressBar.getProgress();
progress += 10;
progressBar.setProgress(progress);
AlterDialog
在当前界面弹出一个对话框,屏蔽掉其他控件的交互,一般用于提示一些重要内容或警告
AlterDialog.Builder dialog = new AlterDialog.Builder(MainActivity.this);
dialog.setTitle("This is dialog");
dialog.setMessage("Something important.");
dialog.setCancelable(false);
dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@override
public void onClick(DialogInterface dialog, int which) {
...
}
});
dialog.setNegaitiveButton("Cancel", new DialogInterface.OnClickListener() {
@override
public void onClick(DialogInterface dialog, int which) {
...
}
});
dialog.show;
四种基本布局
- 线性布局LinearLayout
常用,在线性方向上依次排列,不能在该方向上指定match_parents,否则就填满了
layout_gravity指定控件在布局中的对齐方式,只有相反排列方向的对齐才会生效
layout_weight使用比例的方式指定控件大小,需要将该方向的width/height指定为0dp,weight计算长度是按照所有控件的weight相加,然后用该控件weight/总的数值作为比例显示,还可以将一个设置为wrap,剩下的设置会占据剩余的长度 - 相对布局RelativeLayout
可以相对于父布局,其他控件 - 帧布局
所有控件默认放在右上角 - 百分比布局
引入布局
新建一个title.xml,将布局代码写入
在活动布局代码中写入<include layout="@layout/title" />
最后再活动中将系统自带标题栏隐藏掉
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionbar.hide();
}
创建自定义控件
比如创建一个返回按钮
新建TitleLayout继承自LinearLayout,成为自定义的标题栏控件
public class TitleLayout extends LinearLayout {
public TitleLayout(Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater.from(context).inflate(R.layout.title, this);
//TODO: 点击事件的代码
}
}
先构造,然后使用LayoutInflater.from()构造出一个对象,inflate动态加载布局文件,第一参数是布局文件id,第二参数是父布局,也就是TitleLayout,直接传入this
在布局文件中添加这个自定义控件
<com.example.packetname.TitleLayout
android.layout_width="match_parent"
android.layout_width="wrap_content" />
自定义控件的包名不能省略
ListView
新建一个ListView控件,宽高都设置为match_parent
然后再代码里设置一个String[]数组,并添加一个Adapter
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_list_item_1, data);
ListView listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter);
data是String[]数组,数据可以是数据库提供,也可以是网络下载
数组中的数据无法直接传递给ListView,还需要适配器,android中有很多适配器的实现类
ArrayAdapter是其中一种适配器,第一参数是上下文,第二参数是ListView子项布局的id,最后是适配的数据类型
最后调用ListView的setAdapter方法将构造好的适配器对象传递进入
定制ListView
效果:每个item显示一种水果名称和图片
先定义一个实体类
public class Fruit {
private String name;
private int imageId;
public Fruit(String name, int imageId) {
this.name = name;
this.imageId = imageId;
}
public String getName() {
return name;
}
public int getImageId() {
return imageId;
}
}
定义一个自定义布局fruit_item.xml,定义一个ImageView和TextView
再创建一个自定义的适配器,继承自ArrayAdapter,并将泛型指定为Fruit类
public class FruitAdapter extends ArrayAdapter<Fruit> {
private int resourceId;
public FruitAdapter(Contenxt context, int textViewResourceId,
List<Fruit> objects) {
super(context, textViewResourceId, objects);
resourceId = textViewResourceId;
}
@override
public View getView(int position, View convertView, ViewGroup parent) {
Fruit fruit = getItem(position); //获取当前实例
View view = LayoutInflater.from(getContext()).inflater(resourceId, parent, false);
ImageView fruitImage = (ImageView) view.findViewById(R.id.fruit_image);
TextView fruitName = (TextView) view.findViewById(R.id.fruit_name);
fruitImage.setImageResource(fruit.getImageId());
fruitName.setText(fruit.getName());
return view;
}
}
getView方法是每个子项被滚动到屏幕内的时候会被调用,getView中,getItem是获取当前项的Fruit
提升ListView的运行效率
getView中有一个convertView参数,用于将之前加载好的布局进行缓存,以便之后重用
if (convertView == null) {
view = LayoutInflater.from(getContext()).inflate(resourceId, parent, false);
} else {
view = convertView;
}
还可以借助ViewHolder对这部分进行优化
class ViewHolder {
ImageView fruitImage;
TextView fruitName;
}
ViewHolder viewHolder;
if (convertView = null) {
view = LayoutInflater.from(getContext()).inflate(resourceId, parent, false);
viewHolder = new ViewHolder();
viewHolder.fruitImage = (ImageView) view.findViewById(R.id.fruit_image);
viewHolder.fruitName = (TextView) view.findViewById(R.id.fruit_name);
view.setTag(viewHolder); //将ViewHolder存储在View中
} else {
view = convertView;
viewHolder = (ViewHolder) view.getTag(); //重新获取
}
viewHolder.fruitImage.setImageResource(fruit.getImageId());
viewHolder.fruitName.setText(fruit.getName());
return view;
ListView点击事件
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Fruit fruit = fruitList.get(position); //fruitList是List<Fruit>
//TODO
}
});
RecyclerView
新增的控件,在app/build.gradle文件中,dependencies添加
implementation 'androidx.recyclerview:recyclerview:1.1.0'
布局中添加
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/recycler_view"/>
Fruit类和fruit_item.xml
//Fruit class
public class Fruit {
private String name;
private int imageId;
public Fruit(String name, int imageId) {
this.name = name;
this.imageId = imageId;
}
public String getName() {
return name;
}
public int getImageId() {
return imageId;
}
}
<?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">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/fruit_image"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginLeft="10dp"
android:id="@+id/fruit_name"/>
</LinearLayout>
新建一个适配器FruitAdapter类,继承自RecyclerView.Adapter,泛型指定为FruitAdapter.ViewHolder,是定义的一个内部类
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class FruitAdapter extends RecyclerView.Adapter<FruitAdapter.ViewHolder> {
private List<Fruit> mFruitList;
/*
* ViewHolder继承自RecyclerView.ViewHolder,传入一个View
* view通常是子项的外层布局
* */
static class ViewHolder extends RecyclerView.ViewHolder {
ImageView fruitImage;
TextView fruitName;
public ViewHolder(View view) {
super(view);
fruitImage = (ImageView) view.findViewById(R.id.fruit_image);
fruitName = (TextView) view.findViewById(R.id.fruit_name);
}
}
public FruitAdapter(List<Fruit> fruitList) {
mFruitList = fruitList;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fruit_item,
parent, false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
Fruit fruit = mFruitList.get(position);
holder.fruitImage.setImageResource(fruit.getImageId());
holder.fruitName.setText(fruit.getName());
}
@Override
public int getItemCount() {
return mFruitList.size();
}
}
最后是MainActivity中的代码
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private List<Fruit> fruitList = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initFruit();
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
//LinearLayoutManager用于指定RecyclerView的布局方式
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
FruitAdapter adapter = new FruitAdapter(fruitList);
recyclerView.setAdapter(adapter);
}
private void initFruit() {
for (int i = 0; i < 2; i++) {
Fruit apple = new Fruit("Apple", R.drawable.apple_pic);
fruitList.add(apple);
Fruit banana = new Fruit("Banana", R.drawable.banana_pic);
fruitList.add(banana);
Fruit orange = new Fruit("Orange", R.drawable.orange_pic);
fruitList.add(orange);
Fruit watermelon = new Fruit("Watermelon", R.drawable.watermelon_pic);
fruitList.add(watermelon);
Fruit pear = new Fruit("Pear", R.drawable.pear_pic);
fruitList.add(pear);
Fruit grape = new Fruit("Grape", R.drawable.grape_pic);
fruitList.add(grape);
Fruit pineapple = new Fruit("Pineapple", R.drawable.pineapple_pic);
fruitList.add(pineapple);
Fruit strawberry = new Fruit("Strawberry", R.drawable.strawberry_pic);
fruitList.add(strawberry);
Fruit cherry = new Fruit("Cherry", R.drawable.cherry_pic);
fruitList.add(cherry);
Fruit mango = new Fruit("Mango", R.drawable.mango_pic);
fruitList.add(mango);
}
}
}
横向滚动的瀑布流布局
首先将fruit_item.xml中的元素改成垂直排列
再向主活动添加一句即可
layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
RecyclerView还有网格布局GridLayoutManager和瀑布流布局StaggeredGridLayoutManager
例如瀑布流的实现:
将fruit_item.xml修改几处
首先将LinearLayout的宽度由100dp改成match_parent,因为瀑布流的布局的宽度是很据布局的列数来自动适配的,不是固定值,然后用layout_margin让子项之间留一些距离
接着修改MainActivity代码
StaggeredGridLayoutManager layoutManerger = new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL);
第一参数3是指布局分为3列,第二参数是指定布局的排列方向,最后再setLayoutManager即可
RecyclerView的点击事件
所有的点击事件都需要由具体的View去注册
修改FruitAdapter中的代码
final ViewHolder holder = new ViewHolder(view);
holder.fruitView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int position = holder.getAdapterPosition();
Fruit fruit = mFruitList.get(position);
Toast.makeText(v.getContext(), "u clicked view " + fruit.getName(), Toast.LENGTH_SHORT).show();
}
});
holder.fruitImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int position = holder.getAdapterPosition();
Fruit fruit = mFruitList.get(position);
Toast.makeText(v.getContext(), "u clicked image " + fruit.getName(), Toast.LENGTH_SHORT).show();
}
});
首先修改ViewHolder,添加fruitView变量保存子项最外层布局的实例,然后再onCreateViewHolder()方法中注册点击事件,这里为最外层布局和ImageView都注册了点击事件
点击图片就是Image的注册事件,点击文字因为没有注册,会被子项的最外层布局捕获
界面实践
制作Nine-Patch图片
一种特殊处理过的png图片,能够指定哪些区域可以被拉伸,哪些不可以
在drawable目录下右键图片,点击create 9-patch file即可创建
上边框和左边框便是拉伸的区域,下边框和左边框表示内容防止区域,鼠标拖动图片边缘绘制,按住Shift键拖动擦除
界面代码
界面
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#d8e0e8">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="0dp"
android:id="@+id/msg_recycler_view"
android:layout_weight="1"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:id="@+id/input_text"
android:hint="type something"
android:maxLines="2"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="send"
android:textColor="#000"
android:id="@+id/send"/>
</LinearLayout>
</LinearLayout>
消息类Msg class
public class Msg {
public static final int TYPE_RECEIVED = 0;
public static final int TYPE_SENT = 1;
private String content;
private int type;
public Msg(String content, int type) {
this.content = content;
this.type = type;
}
public String getContent() {
return content;
}
public int getType() {
return type;
}
}
子项布局
<?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="wrap_content">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/left_layout"
android:layout_gravity="left"
android:background="@drawable/message_left">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="10dp"
android:textColor="#fff"
android:id="@+id/left_msg"/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:background="@drawable/message_right"
android:id="@+id/right_layout">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="10dp"
android:id="@+id/right_msg"/>
</LinearLayout>
</LinearLayout>
MsgAdapter
public class MsgAdapter extends RecyclerView.Adapter<MsgAdapter.ViewHolder> {
private List<Msg> mMsgList;
static class ViewHolder extends RecyclerView.ViewHolder {
LinearLayout leftLayout;
LinearLayout rightLayout;
TextView leftMsg;
TextView rightMsg;
public ViewHolder(View view) {
super(view);
leftLayout = (LinearLayout) view.findViewById(R.id.left_layout);
rightLayout = (LinearLayout) view.findViewById(R.id.right_layout);
leftMsg = (TextView) view.findViewById(R.id.left_msg);
rightMsg = (TextView) view.findViewById(R.id.right_msg);
}
}
public MsgAdapter(List<Msg> msgList) {
mMsgList = msgList;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.msg_item, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
Msg msg = mMsgList.get(position);
if (msg.getType() == Msg.TYPE_RECEIVED) {
holder.leftLayout.setVisibility(View.VISIBLE);
holder.rightLayout.setVisibility(View.GONE);
holder.leftMsg.setText(msg.getContent());
} else if (msg.getType() == Msg.TYPE_SENT) {
holder.rightLayout.setVisibility(View.VISIBLE);
holder.leftLayout.setVisibility(View.GONE);
holder.rightMsg.setText(msg.getContent());
}
}
@Override
public int getItemCount() {
return mMsgList.size();
}
}
MainActivity
public class MainActivity extends AppCompatActivity {
private List<Msg> msgList = new ArrayList<>();
private EditText inputText;
private Button send;
private RecyclerView msgRecyclerView;
private MsgAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initMsg();
inputText = (EditText) findViewById(R.id.input_text);
send = (Button) findViewById(R.id.send);
msgRecyclerView = (RecyclerView) findViewById(R.id.msg_recycler_view);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
msgRecyclerView.setLayoutManager(layoutManager);
adapter = new MsgAdapter(msgList);
msgRecyclerView.setAdapter(adapter);
send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String content = inputText.getText().toString();
if (!"".equals(content)) {
Msg msg = new Msg(content, Msg.TYPE_SENT);
msgList.add(msg);
adapter.notifyItemInserted(msgList.size() - 1);
//当有新消息时,刷新RecyclerView的显示
msgRecyclerView.scrollToPosition(msgList.size() - 1);
//定位到最后一行
inputText.setText(""); //清空输入框
}
}
});
}
private void initMsg() {
Msg msg1 = new Msg("Hello guy.", Msg.TYPE_RECEIVED);
msgList.add(msg1);
Msg msg2 = new Msg("Hello! Who is that?", Msg.TYPE_SENT);
msgList.add(msg2);
Msg msg3 = new Msg("This is Tom,. Nice to see you you you you you you you!!!!!!!!", Msg.TYPE_RECEIVED);
msgList.add(msg3);
}
}