《第一行代码》第三章
目录
- 《第一行代码》第三章
- 控件篇
- TextView
- Button
- TextView
- ImageView
- ProgressDialog
- ListView
- 定制ListView
- 更强大的滚动控件——RecyclerView
- 横向
- 瀑布流
- 布局篇
- 线性布局——LinearLayout
- 相对布局——RelativeLayout
- 帧布局——FrameLayout
- 百分比布局
- 自定义
- 自定义布局
界面编写实践——聊天界面在下一篇
控件篇
TextView
- 简单介绍了TextView的几个属性,其余可查阅文档即可
<TextView
android:id="@+id/text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="24sp"
android:textColor="#00ff00"
android:text="Hello World!" />
"match_parent"
为适应父布局,"wrap_content"
为刚好包住文字,即文字大小android:gravity="center"
设置文本位置;android:textSize="24sp"
设置文字大小,以sp为单位;android:textColor="#00ff00"
设置颜色。
Button
- 略
TextView
<EditText
android:id="@+id/edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Type something here"
android:maxLines="2"
android:text="Name" />
android:hint="Type something here"
为提示信息;android:maxLines="2"
为最大行数。
ImageView
<ImageView
android:id="@+id/image_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/img_1"/>
- 修改主活动代码,完成以下效果: 展开查看
private EditText editText;
private ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
imageView = (ImageView) findViewById(R.id.image_view);
editText = (EditText) findViewById(R.id.edit_text);
}@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.button:
imageView.setImageResource(R.drawable.img_2);
break;
default:
break;
}
}
<ProgressBar
android:id="@+id/progress_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="?android:attr/progressBarStyleHorizontal" //设置样式,指定水平进度条,可省
android:max="100" //给进度条设置最大值
/>
- 所有的Android 控件都可以通过android:visibility 进行指定,可选值有三种:visible、invisible 、gone。gone 表示控件不仅不可见,而且不在占用任何屏幕空间。
- 使用 setVisibility()方法可以传入 View.VISIBLE、View.INVISIBLE、View.GONE 来控制可见性。
- 修改主活动case,完成以下效果: 展开查看
case R.id.button:
int progress = progressBar.getProgress();
progress = progress + 10;
progressBar.setProgress(progress);
break;
- 通过AlerDialog.Builder 创建一个AlertDialog 的实例,然后可以为这个对话框设置标题、内容、可否取消等属性。
- 修改case:
case R.id.button:
AlertDialog.Builder dialog = new AlertDialog.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 dialogInterface, int i) {
}
});
dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { //设置取消按钮
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
dialog.show();
break;
ProgressDialog
- 修改case:
case R.id.button:
ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setTitle("This is a ProgressDialog");
progressDialog.setCancelable(true); //设为true即返回就取消
progressDialog.show();
break;
ListView
- 主活动: 展开查看
public class MainActivity extends AppCompatActivity {
private String[] data = {
"Apple","aa","bb","cc","dd","ee","ff","gg","aa","bb","cc","aa","bb","cc","aa","bb","cc"
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayAdapter adapter = new ArrayAdapter(
MainActivity.this, android.R.layout.simple_list_item_1, data);
ListView listView = (ListView) findViewById(R.id.list_view);
listView.setAdapter(adapter);
}
}
定制ListView
- 写Fruit类 展开查看
package com.example.ullayouttest;
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;
}
}
- 重写适配器
public class FruitAdapter extends ArrayAdapter<Fruit> {
private int resourceId;
public FruitAdapter(Context context, int textViewResourceId, List<Fruit> objects){
super(context,textViewResourceId,objects);
resourceId = textViewResourceId;
}
public View getView(int position, View convertView, ViewGroup parent){
Fruit fruit = getItem(position);
View view = LayoutInflater.from(getContext()).inflate(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;
}
}
- 修改主活动:
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);
//主要
initFruits();
FruitAdapter adapter = new FruitAdapter(MainActivity.this,R.layout.fruit_item,fruitList);
ListView listView = (ListView) findViewById(R.id.list_view);
listView.setAdapter(adapter);
//放进ListView
}
private void initFruits(){
for (int i=0;i<2;i++){
Fruit 南瓜 = new Fruit("南瓜",R.drawable.nangua);
fruitList.add(南瓜);
Fruit 土豆 = new Fruit("土豆",R.drawable.tudou);
fruitList.add(土豆);
Fruit 芒果 = new Fruit("芒果",R.drawable.mangguo);
fruitList.add(芒果);
Fruit 菠萝 = new Fruit("菠萝",R.drawable.boluo);
fruitList.add(菠萝);
Fruit 蘑菇 = new Fruit("蘑菇",R.drawable.mogu);
fruitList.add(蘑菇);
Fruit 西瓜 = new Fruit("西瓜",R.drawable.xigua);
fruitList.add(西瓜);
Fruit 饮料 = new Fruit("饮料",R.drawable.yinliao);
fruitList.add(饮料);
}
}
}
- 布局fruit_item:
<?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">
<ImageView
android:id="@+id/fruit_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/fruit_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginLeft="10dp"/>
</LinearLayout>
- 主布局:
<?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">
/>
<ListView
android:id="@+id/list_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
- 修改主活动,优化并加入点击事件(程序不久后自动退出了??)
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);
//主要
initFruits();
FruitAdapter adapter = new FruitAdapter(MainActivity.this,R.layout.fruit_item,fruitList);
ListView listView = (ListView) findViewById(R.id.list_view);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Fruit fruit = fruitList.get(position);
Toast.makeText(MainActivity.this,fruit.getName(),
Toast.LENGTH_SHORT).show();
}
});
}
更强大的滚动控件——RecyclerView
- 修改主活动中onCreate
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);
//主要
initFruits();
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.rc_list);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
FruitAdapter adapter = new FruitAdapter(fruitList);
recyclerView.setAdapter(adapter);
}
- 修改FruitAdapter: 展开
package com.example.ullayouttest;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
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 {
private List mFruitList;
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 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();
}
}
- 主布局(书里的是android.support.xxx):
<?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">
/>
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/rc_list"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
横向
- 修改fruit_item 布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="100dp"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/fruit_image"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_gravity="center_horizontal"
/>
<TextView
android:id="@+id/fruit_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginLeft="10dp"/>
</LinearLayout>
- 在主活动OnCreate中添加
layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
语句
瀑布流
- 修改主活动,修改的主要代码只有一句,即
StaggeredGridLayoutManager layoutManager
修改成瀑布流。 展开
public class MainActivity extends AppCompatActivity {
private List fruitList = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initFruits();
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.rc_list);
StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(3,StaggeredGridLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
FruitAdapter adapter = new FruitAdapter(fruitList);
recyclerView.setAdapter(adapter);
}
private void initFruits(){
for (int i=0;i<2;i++){
Fruit 南瓜 = new Fruit( getRandomLengthName("南瓜"),R.drawable.nangua);
fruitList.add(南瓜);
Fruit 土豆 = new Fruit(getRandomLengthName("土豆"),R.drawable.tudou);
fruitList.add(土豆);
Fruit 芒果 = new Fruit(getRandomLengthName("芒果"),R.drawable.mangguo);
fruitList.add(芒果);
Fruit 菠萝 = new Fruit(getRandomLengthName("菠萝"),R.drawable.boluo);
fruitList.add(菠萝);
Fruit 蘑菇 = new Fruit(getRandomLengthName("蘑菇"),R.drawable.mogu);
fruitList.add(蘑菇);
Fruit 西瓜 = new Fruit(getRandomLengthName("西瓜"),R.drawable.xigua);
fruitList.add(西瓜);
Fruit 饮料 = new Fruit(getRandomLengthName("饮料"),R.drawable.yinliao);
fruitList.add(饮料);
}
}
private String getRandomLengthName(String name){
Random random = new Random();
int length = random.nextInt(20) + 1;
StringBuilder builder = new StringBuilder();
for(int i = 0;i<length;i++){ builder.append(name);
}
return= builder.tostring();
}
}
- 瀑布流添加事件:与ListView有所不同,需要给子项具体的View添加点击事件 展开
public class FruitAdapter extends RecyclerView.Adapter {
private List mFruitList;
static class ViewHolder extends RecyclerView.ViewHolder{
View fruitView;
ImageView fruitImage;
TextView fruitName;
public ViewHolder(View view){
super(view);
fruitView = view;
fruitImage = (ImageView) view.findViewById(R.id.fruit_image);
fruitName = (TextView)view.findViewById(R.id.fruit_name);
}
}
public FruitAdapter(List 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);
final ViewHolder holder = new ViewHolder(view);
holder.fruitView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int position = holder.getAdapterPosition();
Fruit fruit = mFruitList.get(position);
Toast.makeText(view.getContext(),"you clicked view"+fruit.getName(),Toast.LENGTH_SHORT).show();
}
});
holder.fruitImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int position = holder.getAdapterPosition();
Fruit fruit = mFruitList.get(position);
Toast.makeText(view.getContext(),"you clicked image"+fruit.getName(),Toast.LENGTH_SHORT).show();
}
});
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();
}
}
布局篇
线性布局——LinearLayout
- 通过
android:orientation="vertical"
可改变为水平排列布局。 android:layout_gravity
用于指定控件在布局中的对齐方式。android:layout_weight
可使用比例的方式来指定控件的大小。
相对布局——RelativeLayout
<!--相对父布局进行对齐-->
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_centerInParent="true"
<!--相对控件进行对齐-->
android:layout_above="@id/button3"
android:layout_toLeftOf="@id/button3"
android:layout_below="@id/button3"
android:layout_toRightOf="@id/button3"
帧布局——FrameLayout
- 所有的控件都默认摆放在布局的左上角
百分比布局
- 百分比布局————android.support.percent.PercentFrameLayout
layout_widthPercent="50%"
layout_heightPercent="50%"
自定义
自定义布局
- 当要添加标题栏,主活动中:
ActionBar actionBar = getSupportActionBar();
if(actionBar != null){
actionBar.hide();
}
- 主活动布局添加:
<include layout="@layout/title"/>
- 布局:
android:background="@drawable/title"
自定义控件
- 添加新的布局
<?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="wrap_content"
android:background="@drawable/title">
<Button
android:id="@+id/back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="5dp"
android:background="@drawable/back"
android:text="Back"
android:textColor="#fff"/>
<TextView
android:id="@+id/text"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:gravity="center"
android:text="Title Text"
android:textColor="#fff"
android:textSize="24sp"/>
<Button
android:id="@+id/edit"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:layout_margin="5dp"
android:background="@drawable/edit"
android:text="Edit"
android:textColor="#fff"/>
</LinearLayout>
- 新建活动并写好相应的功能 展开查看
package com.example.ullayouttest;
import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;
public class TitleLayout extends LinearLayout {
public TitleLayout(Context context, AttributeSet attrs){
super(context,attrs);
LayoutInflater.from(context).inflate(R.layout.title,this);
Button titleBack = (Button) findViewById(R.id.back);
Button titleEdit = (Button) findViewById(R.id.edit);
titleBack.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
((Activity)getContext()).finish();
}
});
titleEdit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getContext(), "you clicked edit button", Toast.LENGTH_SHORT).show();
}
});
}
}
- 接下来当作普通控件使用即可
<com.example.ullayouttest.TitleLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"/>