《第一行代码--android》笔记·第三章:UI

目录

 

3.2常用控件介绍

3.2.1 TextView

3.2.2 Button

3.2.3 EditText

3.2.4 ImageView

3.2.5 ProgressBar

3.2.6 AlertDialog

3.2.7 ProgressDialog

3.3布局

3.5ListView

3.6RecyclerView


3.2常用控件介绍

3.2.1 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="This is TextView"/>

layout_width,layout_height:控件宽高,match_parent与父布局相等,wrap_content刚好容纳下内容。

gravity:文字对齐方式,top,bottom,left,right,center。

textSize:文字大小(以sp为单位)。

textColor:指定文字颜色。

3.2.2 Button

<Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="button"
        android:textAllCaps="false"
        />

按钮文本默认转为大写,使用android:textAllCaps="false"改变。

注册监听器事件

%method one
Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

%method tow,implements View.OnClickListener
public void onClick(View v){
    switch(v.getId()){
        case R.id.button:
            break;
        default:
            break;
    }
}
onCreate(){
    Button button = (Button) findViewById(R.id.button);
    button.setOnClickListener(this);
}

3.2.3 EditText

<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:hint:提示性文本

android:maxLines:最大行数

3.2.4 ImageView

<ImageView
        android:id="@+id/image_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/img_1"
        />

3.2.5 ProgressBar

<ProgressBar
        android:id="@+id/progress_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        style="?android:attr/progressBarStyleHorizontal"
        android:max="100"
        />

style:设置进度条样式

android:visibility:visible可见,invisible不可见但占据空间,gone不可见不占据空间。

progressBar.setVisibility(View.GONE);修改进度条可见性。

3.2.6 AlertDialog

弹出对话框,屏蔽掉其他控件的交互能力。

button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        switch(v.getId()){
            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 dialog, int which) {}
                });
                dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener()             
                {
                     @Override
                     public void onClick(DialogInterface dialog, int which) {}
                });
                dialog.show();
                break;
            default:
                break;
            }
    }
});

AlertDialog.Builder创建一个AlertDialog实例。

setPositiveButton()确定按钮点击事件。

setNegativeButton()取消按钮点击事件。

3.2.7 ProgressDialog

弹出对话框,屏蔽掉其他控件的交互能力,显示一个进度条。

button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.button:   
                ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
                progressDialog.setTitle("This is ProgressDialog");
                progressDialog.setMessage("loading..");
                progressDialog.setCancelable(true);
                progressDialog.show();
                break;
            default:
                break;
        }
    }
});

setCancelable(false)表示对话框不能通过返回键退出,在加载完程序后添加dismiss()方法来关闭对话框。

3.3布局

LinearLayout:线性布局

android:orientation:vertical垂直方向(高度不能为match_parent),horizontal水平方向(宽度不能为match_parent)

android:layout_gravity:对齐方式,vertical不能改变垂直方向对齐方式,horizontal不能改变水平方向对齐方式。

android:layout_wight:权重,控制控件大小(限制与orientation类似)(android:layout_width="0dp"等)。

RelativeLayout:相对布局

相对于布局

android:layout_alignParentLeft(RIght,Top,Bottom)="true"

android:layout_centerInParent="true"

相对控件

layout_above,layout_below,layout_toRightOf,layout_toLeftOf = "@id/"

边界对齐

FrameLayout:帧布局

控件默认放在左上角,可叠加

RecentFrameLayout:百分比布局

添加库

在app/build.gradle中的dependencies添加

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:24.2.1'
    compile 'com.android.support:design:24.2.1'

    compile 'com.android.support:percent:24.2.1'

    testCompile 'junit:junit:4.12'
}
xmlns:app="http://schemas.android.com/apk/res-auto"定义一个app的命名空间

app:layout_widthPercent="50%"

app:layout_heightPercent="50%"

3.5ListView

3.5.1简单实例

activity_main.xml里注册ListView

 private String[] data = {"Apple","Banana","Orange","Watermelon","Pear","Grape","Pineaapple","Strawberry","Cerry","Mango",
            "Apple","Banana","Orange","Watermelon","Pear","Grape","Pineaapple","Strawberry","Cerry","Mango"};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,data);
        ListView listView = (ListView) findViewById(R.id.list_view);
        listView.setAdapter(adapter);
    }

ArrayAdapter(Context context, int resource, T[] objects)

context The current context.
resource The resource ID for a layout file containing a TextView to use when instantiating views.
objects The objects to represent in the ListView.

android.R.layout.simple.list_item_1为ListView子项布局的id,Android内置布局文件,只有一个TextView。

定制ListView界面:

重写适配器:

public View getView(int position, View convertView, ViewGroup parent) {
        Fruit fruit = getItem(position); // 获取当前项的Fruit实例
        View view;
        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
        }
        viewHolder.fruitImage.setImageResource(fruit.getImageId());
        viewHolder.fruitName.setText(fruit.getName());
        return view;
    }

    class ViewHolder {

        ImageView fruitImage;

        TextView fruitName;

    }

getView():用来加载数据。

convertView:用来缓存之前加载好的视图。

ViewGroup:可扩展的视图。

ViewHolder:用来缓存控件的实例。

LayoutInflater.from(getContext()).inflate(resourceId, parent, false)

from(getContext());返回当前上下文的LayoutInflater对象

inflate():从指定的xml资源中扩展新的视图层次结构

resource ID for an XML layout resource to load (e.g., R.layout.main_page)
root Optional view to be the parent of the generated hierarchy (if attachToRoot is true), or else simply an object that provides a set of LayoutParams values for root of the returned hierarchy (if attachToRoot is false.)
attachToRoot Whether the inflated hierarchy should be attached to the root parameter? If false, root is only used to create the correct subclass of LayoutParams for the root view in the XML.

3.6RecyclerView

public class FruitAdapter extends RecyclerView.Adapter<FruitAdapter.ViewHolder>{

    private List<Fruit> 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<Fruit> fruitList) {
        mFruitList = fruitList;
    }

    @Override
    public ViewHolder onCreateViewHolder(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 v) {
                int position = holder.getAdapterPosition();
                Fruit fruit = mFruitList.get(position);
                Toast.makeText(v.getContext(), "you 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(), "you clicked image " + fruit.getName(), Toast.LENGTH_SHORT).show();
            }
        });
        return holder;
    }

    @Override
    public void onBindViewHolder(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();
    }

}

onCreateViewHolder():将布局加载进来,并且创建一个ViewHolder对象。

onBindViewHolder():对子项赋值,在每个子项滚动到屏幕时执行。

getItemCount():返回RecyclerView子项数。

android:marginTop = "10dp"    控制间距。

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initFruits();
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        StaggeredGridLayoutManager layoutManager = new
                StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        FruitAdapter adapter = new FruitAdapter(fruitList);
        recyclerView.setAdapter(adapter);
    }

LayoutManager:管理布局。

setOrientation:设置布局排列方式。

LinearLayoutManager:流式布局。

StaggeredGridLayoutManager:瀑布流式布局。

GridLayoutManager:网格布局。

adapter.notifyItemInserted();通知列表有新的数据插入。

RecyclerView.scrollToPosition();将显示的数据定位到最后一行。

猜你喜欢

转载自blog.csdn.net/fingers_xwk/article/details/81586801