Android的View 简单理解和实例

本文介绍了Android开发的基础知识,包括View的基本概念、如何在Activity中获取和设置View对象、设置View属性的方法以及为View添加监听器的过程。通过一个具体的示例应用,展示了如何使用Java和XML布局文件来创建简单的Android应用程序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.View的基本概念
在Activity显示的控件 都叫做View(View类 是所有的控件类的父类 比如 文本 按钮)

2.在Activity当中获取代表View的对象
Activity读取布局文件生成相对应的 各种View对象
TextView textView=(TextView)findViewBy(R.id.textView)

3.设置view的属性

Activity_mian.xml 这样的xml布局文件中发现了,类似@+id/和@id/到底有什么区别呢? 这里@可以理解为引用,而多出的+代表自己新声明的

4.为View设置监听器
一个控件可以绑定多个监听器 不通过的监听器响应不同的事件

获取代表控件的对象
定义一个类,实现监听接口 implements OnClickListener
生成监听对象

为控件绑定监听对象


改成垂直布局

布局文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="80px"
        android:background="#FF0000"
        android:text="hello_world 熊" />
    
    <Button 
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="点击"/>

</LinearLayout>

MianActivity文件
package com.xiong.fisrt_android;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

	private TextView textView;
	private Button button;
	private int count = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		textView = (TextView) findViewById(R.id.textView);
		button = (Button) findViewById(R.id.button);
		textView.setText("hello  Android!!!");
		textView.setBackgroundColor(Color.BLUE);
		ButtoneListener buttoneListener = new ButtoneListener();// 生成监听对象
		button.setOnClickListener(buttoneListener);// 按钮绑定一个监听器
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	class ButtoneListener implements OnClickListener// 创建一个类实现监听事件的接口
	{

		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			count++;
			textView.setText(Integer.toString(count));

		}

	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值