首页 文章 精选 留言 我的

精选列表

搜索[socket编程],共10000篇文章
优秀的个人博客,低调大师

☕【Java深层系列】「并发编程系列」让我们一起探索一下CountDownLatch的技术原理和源码分析

CountDownLatch工作原理分析 一、大致介绍 那么本篇文章和大家分享分析一下JDK1.8的CountDownLatch的工作原理; 简单认识CountDownLatch 何为CountDownLatch? CountDownLatch从字面上理解,count计数做down的减法动作,而Latch又是门闩的意思; CountDownLatch是一种同步帮助,允许一个或多个线程等待,直到在其他线程中执行的一组操作完成; CountDownLatch内部没有所谓的公平锁\非公平锁的静态内部类,只有一个Sync静态内部类,CountDownLatch内部基本上也是通过sync.xxx之类的这种调用方式的; CountDownLatch内部维护了一个虚拟的资源池,如果许可数不为为0一直线程阻塞等待,直到许可数为0时才释放继续往下执行; CountDownLatch的state关键词 其实CountDownLatch的实现也恰恰很好利用了其父类AQS的state变量值; 初始化一个数量值作为计数器的默认值,假设为N,那么当任何线程调用一次countDown则计数值减1,直到许可为0时才释放等待; CountDownLatch,简单大致意思为:A组线程等待另外B组线程,B组线程执行完了,A组线程才可以执行; 常用重要的方法 创建一个给定许计数值的计数同步器对象 public CountDownLatch(int count) 入队等待,直到计数器值为0则释放等待 public void await() 释放许可,计数器值减1,若计数器值为0则触发释放无用结点 public void countDown() 获取目前最新的共享资源计数器值 public long getCount() 设计与实现伪代码 获取共享锁: 如果检测中断状态发现被中断过的话,那么则抛出InterruptedException异常 如果尝试获取共享锁失败的话( 尝试获取共享锁的各种方式由AQS的子类实现 ), 那么就新增共享锁结点通过自旋操作加入到队列中,然后通过调用LockSupport.park进入阻塞等待,直到计数器值为零才释放等待 public void await() throws InterruptedException { sync.acquireSharedInterruptibly(1); } 释放共享锁: 如果尝试释放共享锁失败的话( 尝试释放共享锁的各种方式由AQS的子类实现 ), 那么通过自旋操作完成阻塞线程的唤起操作 public void countDown() { sync.releaseShared(1); } CountDownLatch生活细节化理解 比如百米赛跑,我就以赛跑为例生活化阐述该CountDownLatch原理: 1、场景:百米赛跑十人参赛,终点处有一个裁判计数; 2、开跑一声起跑信号,十个人争先恐后的向终点跑去,真的是振奋多秒,令人振奋; 3、当一个人到达终点,这个人就完成了他的赛跑事情了,就没事一边玩去了,那么裁判则减去一个人; 4、随着人员陆陆续续的都跑到了终点,最后裁判计数显示还有0个人未到达,意思就是人员都达到了; 5、然后裁判就拿着登记的成绩屁颠屁颠去输入电脑登记了; 6、到此打止,这一系列的动作认为是A组线程等待另外其他组线程的操作,直到计数器为零,那么A则再干其他事情; 源码分析CountDownLatch CountDownLatch构造器 构造器源码: /** * Constructs a {@code CountDownLatch} initialized with the given count. * * @param count the number of times {@link #countDown} must be invoked * before threads can pass through {@link #await} * @throws IllegalArgumentException if {@code count} is negative */ public CountDownLatch(int count) { if (count < 0) throw new IllegalArgumentException("count < 0"); this.sync = new Sync(count); } 2、创建一个给定许计数值的计数同步器对象,计数器值必须大于零,count值最后赋值给了state这个共享资源值; Sync同步器 AQS --> Sync CountDownLatch内的同步器都是通过Sync抽象接口来操作调用关系的,细看会发现基本上都是通过sync.xxx之类的这种调用方式的; await() 源码 /** * Causes the current thread to wait until the latch has counted down to * zero, unless the thread is {@linkplain Thread#interrupt interrupted}. * * // 导致当前线程等待,直到计数器值减为零则释放等待,或者由于线程被中断也可导致释放等待; * * <p>If the current count is zero then this method returns immediately. * * <p>If the current count is greater than zero then the current * thread becomes disabled for thread scheduling purposes and lies * dormant until one of two things happen: * <ul> * <li>The count reaches zero due to invocations of the * {@link #countDown} method; or * <li>Some other thread {@linkplain Thread#interrupt interrupts} * the current thread. * </ul> * * <p>If the current thread: * <ul> * <li>has its interrupted status set on entry to this method; or * <li>is {@linkplain Thread#interrupt interrupted} while waiting, * </ul> * then {@link InterruptedException} is thrown and the current thread's * interrupted status is cleared. * * @throws InterruptedException if the current thread is interrupted * while waiting */ public void await() throws InterruptedException { sync.acquireSharedInterruptibly(1); } await此方法被调用后,则一直会处于等待状态,其核心还是由于调用了LockSupport.park进入阻塞等待; 当计数器值state=0时可以打破等待现状,当然还有线程被中断后也可以打破线程等待现状; acquireSharedInterruptibly(int) 源码: /** * Acquires in shared mode, aborting if interrupted. Implemented * by first checking interrupt status, then invoking at least once * {@link #tryAcquireShared}, returning on success. Otherwise the * thread is queued, possibly repeatedly blocking and unblocking, * invoking {@link #tryAcquireShared} until success or the thread * is interrupted. * @param arg the acquire argument. * This value is conveyed to {@link #tryAcquireShared} but is * otherwise uninterpreted and can represent anything * you like. * @throws InterruptedException if the current thread is interrupted */ public final void acquireSharedInterruptibly(int arg) throws InterruptedException { if (Thread.interrupted()) // 调用之前先检测该线程中断标志位,检测该线程在之前是否被中断过 throw new InterruptedException(); // 若被中断过的话,则抛出中断异常 if (tryAcquireShared(arg) < 0) // 尝试获取共享资源锁,小于0则获取失败,此方法由AQS的具体子类实现 doAcquireSharedInterruptibly(arg); // 将尝试获取锁资源的线程进行入队操作 } 由于是实现同步计数器功能,所以tryAcquireShared首次调用必定小于0,则就顺利了进入了doAcquireSharedInterruptibly线程等待; 至于首次调用为什么会小于0,请看子类的实现,子类的实现判断为 "(getState() == 0) ? 1 : -1" ; 3.5、tryAcquireShared(int) 源码 protected int tryAcquireShared(int acquires) { return (getState() == 0) ? 1 : -1; // 计数器值与零比较判断,小于零则获取锁失败,大于零则获取锁成功 } 尝试获取共享锁资源,但是在计数器CountDownLatch这个功能中,小于零则需要入队,进入阻塞队列进行等待;大于零则唤醒等待队列,释放await方法的阻塞等待; doAcquireSharedInterruptibly(int) 源码 /** * Acquires in shared interruptible mode. * @param arg the acquire argument */ private void doAcquireSharedInterruptibly(int arg) throws InterruptedException { // 按照给定的mode模式创建新的结点,模式有两种:Node.EXCLUSIVE独占模式、Node.SHARED共享模式; final Node node = addWaiter(Node.SHARED); // 创建共享模式的结点 boolean failed = true; try { for (;;) { // 自旋的死循环操作方式 final Node p = node.predecessor(); // 获取结点的前驱结点 if (p == head) { // 若前驱结点为head的话,那么说明当前结点自然不用说了,仅次于老大之后的便是老二了咯 int r = tryAcquireShared(arg); // 而且老二也希望尝试去获取一下锁,万一头结点恰巧刚刚释放呢?希望还是要有的,万一实现了呢 if (r >= 0) { // 若r>=0,说明已经成功的获取到了共享锁资源 setHeadAndPropagate(node, r); // 把当前node结点设置为头结点,并且调用doReleaseShared释放一下无用的结点 p.next = null; // help GC failed = false; return; } // 但是在await方法首次被调用会流转到此,这个时候获取锁资源会失败,即r<0,所以会进入是否需要休眠的判断 // 但是第一次进入休眠方法,因为被创建的结点waitStatus=0,所以会被修改一次为SIGNAL状态,再次循环一次 // 而第二次循环进入shouldParkAfterFailedAcquire方法时,返回true就是需要休眠,则顺利调用park方式阻塞等待 } if (shouldParkAfterFailedAcquire(p, node) && // 根据前驱结点看看是否需要休息一会儿 parkAndCheckInterrupt()) // 阻塞操作,正常情况下,获取不到共享锁,代码就在该方法停止了,直到被唤醒 // 被唤醒后,发现parkAndCheckInterrupt()里面检测了被中断了的话,则补上中断异常,因此抛了个异常 throw new InterruptedException(); } } finally { if (failed) cancelAcquire(node); } } doAcquireSharedInterruptibly在实现计数器原理的时候,主要的干的事情就是等待再等待,等到计数器值为零时才苏醒; countDown() 源码 /** * Decrements the count of the latch, releasing all waiting threads if * the count reaches zero. * * <p>If the current count is greater than zero then it is decremented. * If the new count is zero then all waiting threads are re-enabled for * thread scheduling purposes. * * <p>If the current count equals zero then nothing happens. */ public void countDown() { sync.releaseShared(1); // 释放一个许可资源 } 释放许可资源,也就是计数器值不断的做减1操作,当计数器值为零的时候,该方法将会释放所有正在等待的线程队列;至于为什么还会释放所有,请看后续的releaseShared(int arg)讲解; releaseShared(int) 源码: /** * Releases in shared mode. Implemented by unblocking one or more * threads if {@link #tryReleaseShared} returns true. * * @param arg the release argument. This value is conveyed to * {@link #tryReleaseShared} but is otherwise uninterpreted * and can represent anything you like. * @return the value returned from {@link #tryReleaseShared} */ public final boolean releaseShared(int arg) { if (tryReleaseShared(arg)) { // 尝试释放共享锁资源,此方法由AQS的具体子类实现 doReleaseShared(); // 自旋操作,唤醒后继结点 return true; // 返回true表明所有线程已释放 } return false; // 返回false表明目前还没释放完全,只要计数器值不为零的话,那么都会返回false } releaseShared方法首先就判断了tryReleaseShared(arg)的返回值,但是计数器值只要不为零,都会返回false,因此releaseShared该方法就立马返回false了; 所以当计数器值慢慢减至零时,则立马返回true,那么也就立马会调用doReleaseShared释放所有等待的线程队列; tryReleaseShared(int) 源码: // CountDownLatch 的静态内部类 Sync 类的 tryReleaseShared 方法 protected boolean tryReleaseShared(int releases) { // Decrement count; signal when transition to zero for (;;) { // 自旋的死循环操作方式 int c = getState(); // 获取最新的计数器值 if (c == 0) // 若计数器值为零,说明已经通过CAS操作减至零了,所以在并发中读取到零时并不需要做什么操作,因此返回false return false; int nextc = c-1; // 计数器值减1操作 if (compareAndSetState(c, nextc)) // 通过CAS比较,顺利情况下设置成功返回true return nextc == 0; // 当通过计算操作得到的nextc为零时通过CAS修改成功,那么表明所有事情都已经做完,需要释放所有等待的线程队列 // 若CAS失败,想都不用想肯定是由于并发操作,导致CAS失败,那么唯一可做的就是下一次循环查看是否已经被其他线程处理了 } } CountDownLatch的静态内部类实现父类AQS的方法,用来处理如何释放锁,笼统的讲,若返回负数则需要进入阻塞队列,否则需要释放所有等待队列; doReleaseShared() 主要目的是释放线程中所有等待的队列,当计数器值为零时,此方法马上会被调用,通过自旋方式轮询干掉所有等待的队列; /** * Release action for shared mode -- signals successor and ensures * propagation. (Note: For exclusive mode, release just amounts * to calling unparkSuccessor of head if it needs signal.) */ private void doReleaseShared() { /* * Ensure that a release propagates, even if there are other * in-progress acquires/releases. This proceeds in the usual * way of trying to unparkSuccessor of head if it needs * signal. But if it does not, status is set to PROPAGATE to * ensure that upon release, propagation continues. * Additionally, we must loop in case a new node is added * while we are doing this. Also, unlike other uses of * unparkSuccessor, we need to know if CAS to reset status * fails, if so rechecking. */ for (;;) { // 自旋的死循环操作方式 Node h = head; // 每次都是取出队列的头结点 if (h != null && h != tail) { // 若头结点不为空且也不是队尾结点 int ws = h.waitStatus; // 那么则获取头结点的waitStatus状态值 if (ws == Node.SIGNAL) { // 若头结点是SIGNAL状态则意味着头结点的后继结点需要被唤醒了 // 通过CAS尝试设置头结点的状态为空状态,失败的话,则继续循环,因为并发有可能其它地方也在进行释放操作 if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0)) continue; // loop to recheck cases unparkSuccessor(h); // 唤醒头结点的后继结点 } // 如头结点为空状态,则把其改为PROPAGATE状态,失败的则可能是因为并发而被改动过,则再次循环处理 else if (ws == 0 && !compareAndSetWaitStatus(h, 0, Node.PROPAGATE)) continue; // loop on failed CAS } // 若头结点没有发生什么变化,则说明上述设置已经完成,大功告成,功成身退 // 若发生了变化,可能是操作过程中头结点有了新增或者啥的,那么则必须进行重试,以保证唤醒动作可以延续传递 if (h == head) // loop if head changed break; } } 总结 1、有了分析AQS的基础后,再来分析CountDownLatch便快了很多; 2、在这里我简要总结一下CountDownLatch的流程的一些特性: • 管理一个大于零的计数器值; • 每countDown一次则state就减1一次,直到许可证数量等于0则释放队列中所有的等待线程; • 也可以通过countDown/await组合一起使用,来实现CyclicBarrier的功能; CountDownLatch用法 CountDownLatch类只提供了一个构造器: public CountDownLatch(int count) { }; //参数count为计数值 然后下面这3个方法是CountDownLatch类中最重要的方法: public void await() throws InterruptedException { }; //调用await()方法的线程会被挂起,它会等待直到count值为0才继续执行 public boolean await(long timeout, TimeUnit unit) throws InterruptedException { }; //和await()类似,只不过等待一定的时间后count值还没变为0的话就会继续执行 public void countDown() { }; //将count值减1 CountDownLatch, 一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。 举个例子说明: package main.java.CountDownLatch; import java.util.concurrent.CountDownLatch; public class countDownlatchTest { public static void main(String[] args) throws InterruptedException { CountDownLatch countDownLatch = new CountDownLatch(5); for(int i=0;i<5;i++){ new Thread(new readNum(i,countDownLatch)).start(); } countDownLatch.await(); System.out.println("线程执行结束。。。。"); } static class readNum implements Runnable{ private int id; private CountDownLatch latch; public readNum(int id,CountDownLatch latch){ this.id = id; this.latch = latch; } @Override public void run() { synchronized (this){ System.out.println("id:"+id); latch.countDown(); System.out.println("线程组任务"+id+"结束,其他任务继续"); } } } } 输出结果: id:1 线程组任务1结束,其他任务继续 id:0 线程组任务0结束,其他任务继续 id:2 线程组任务2结束,其他任务继续 id:3 线程组任务3结束,其他任务继续 id:4 线程组任务4结束,其他任务继续 线程执行结束。。。。 线程在countDown()之后,会继续执行自己的任务

优秀的个人博客,低调大师

Go 开发关键技术指南 | 带着服务器编程金刚经走进 2020 年(内含超全知识大图)

作者 |杨成立(忘篱) 阿里巴巴高级技术专家 关注“阿里巴巴云原生”公众号,回复 Go即可查看清晰知识大图! 导读:从问题本身出发,不局限于 Go 语言,探讨服务器中常常遇到的问题,最后回到 Go 如何解决这些问题,为大家提供 Go 开发的关键技术指南。我们将以系列文章的形式推出《Go 开发的关键技术指南》,共有 4 篇文章,本文为第 3 篇。 Go 开发指南 Interfaces Go 在类型和接口上的思考是: Go 类型系统并不是一般意义的 OO,并不支持虚函数; Go 的接口是隐含实现,更灵活,更便于适配和替换; Go 支持的是组合、小接口、组合+小接口; 接口设计应该考虑正交性,组合更利于正交性。 Type System Go 的类型系统是比较容易和 C++/Java 混淆的,特别是习惯于类体系和虚函数的思路后,很容易想在 Go 走这个路子

优秀的个人博客,低调大师

【读书笔记《Android游戏编程之从零开始》】4.Android 游戏开发常用的系统控件(EditText、CheckBox、Radiob...

3.4 EditText EditText类官方文档地址:http://developer.android.com/reference/android/widget/EditText.html EditText继承TextView,所以EditText具有TextView的属性特点,下面主要介绍一些EditText的特有的输入法的属性特点 android:layout_gravity="center_vertical":设置控件显示的位置:默认top,这里居中显示,还有bottom android:hin:Text为空时显示的文字提示信息,可通过textColorHint设置提示信息的颜色。 android:singleLine:设置单行输入,一旦设置为true,则文字不会自动换行。 android:gray="top" :多行中指针在第一行第一位置et.setSelection(et.length());:调整光标到最后一行 android:autoText :自动拼写帮助。这里单独设置是没有效果的,可能需要其他输入法辅助才行 android:capitalize :设置英文字母大写类型。设置如下值:sentences仅第一个字母大写;words每一个单词首字母大小,用空格区分单词;characters每一个英文字母都大写。 android:digits :设置允许输入哪些字符。如“1234567890.+-*/%\n()” android:singleLine :是否单行或者多行,回车是离开文本框还是文本框增加新行android:numeric :如果被设置,该TextView接收数字输入。有如下值设置:integer正整数、signed带符号整数、decimal带小数点浮点数。 android:inputType:设置文本的类型 android:password :密码,以小点”.”显示文本 android:phoneNumber :设置为电话号码的输入方式。 android:editable :设置是否可编辑。仍然可以获取光标,但是无法输入。 android:autoLink=”all” :设置文本超链接样式当点击网址时,跳向该网址 android:textColor = "#ff8c00":字体颜色 android:textStyle="bold":字体,bold, italic, bolditalic android:textAlign="center":EditText没有这个属性,但TextView有 android:textColorHighlight="#cccccc":被选中文字的底色,默认为蓝色 android:textColorHint="#ffff00":设置提示信息文字的颜色,默认为灰色 android:textScaleX="1.5":控制字与字之间的间距 android:typeface="monospace":字型,normal, sans, serif, monospace android:background="@null":空间背景,这里没有,指透明 android:layout_weight="1":权重在控制控件显示的大小时蛮有用的。 android:textAppearance="?android:attr/textAppearanceLargeInverse":文字外观,这里引用的是系统自带的一个外观,?表示系统是否有这种外观,否则使用默认的外观。 <?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" > <TextView android:id="@+id/tv" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/hello_world" /> <EditText android:id="@+id/et" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/txt_hint" /> <Button android:id="@+id/btn" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/btn_GetEditTextStr" /> </LinearLayout> public class MainActivity extends Activity { private EditText et; // 创建一个文本编辑器对象 private Button btn; private TextView tv; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); et = (EditText) findViewById(R.id.et); btn = (Button) findViewById(R.id.btn); tv = (TextView) findViewById(R.id.tv); btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub // 获取EditText中的文本内容 String str = et.getText().toString(); // 让TextView将获取到的EditText内容str显示出来 tv.setText(str); } }); } } 3.5 CheckBox CheckBox类官方文档地址:http://developer.android.com/reference/android/widget/CheckBox.html <?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" > <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/hello_world" /> <CheckBox android:id="@+id/cb1" android:layout_width="match_parent" android:layout_height="wrap_content" android:button="@drawable/checkboxstyle" android:text="@string/checkbox1" /> <CheckBox android:id="@+id/cb2" android:layout_width="match_parent" android:layout_height="wrap_content" android:button="@drawable/checkboxstyle" android:text="@string/checkbox2" /> <CheckBox android:id="@+id/cb3" android:layout_width="match_parent" android:layout_height="wrap_content" android:button="@drawable/checkboxstyle" android:text="@string/checkbox3" /> </LinearLayout> import android.app.Activity; import android.os.Bundle; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.Toast; public class MainActivity extends Activity implements OnCheckedChangeListener { private CheckBox cb1, cb2, cb3; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 实例化3个CheckBox cb1 = (CheckBox) findViewById(R.id.cb1); cb2 = (CheckBox) findViewById(R.id.cb2); cb3 = (CheckBox) findViewById(R.id.cb3); cb1.setOnCheckedChangeListener(this); cb2.setOnCheckedChangeListener(this); cb3.setOnCheckedChangeListener(this); } // 重写监听器的抽象函数 /* * onCheckedChanged(CompoundButton buttonView, boolean isChecked) * 第一个参数确定哪一个CheckBox状态发生改变 第二个参数确定改变的CheckBox的具体状态值,true为勾选,false为未勾选。 */ @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // buttonView 选中状态发生改变的那个按钮 // isChecked 表示按钮新的状态(true/false) if (cb1 == buttonView || cb2 == buttonView || cb3 == buttonView) { if (isChecked) { // 显示一个提示消息 toastDisplay(buttonView.getText() + "选中"); } else { toastDisplay(buttonView.getText() + "取消选中"); } } } private void toastDisplay(String str) { /* * Toast.makeText(Context context, CharSequence text,int duration); * 第一个参数是上下文对象 第二个参数是显示的文本内容 * 第三个参数是显示提示消息的持续时间;其值有2个参数LENGTH_SHORT(短暂持续)和LENGTH_LONG(略长持续): * 最后,使用Toast对象调用show()方法即可 */ Toast.makeText(this, str, Toast.LENGTH_SHORT).show(); } } CheckBox样式修改: 在res/drawable中添加checkbox自定义样式的xml文件。 <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <!-- 选中状态样式 --> <item android:drawable="@drawable/checkbox_checked" android:state_checked="true"></item> <!-- 未选中状态样式 --> <item android:drawable="@drawable/checkbox_normol" android:state_checked="false"></item> </selector> 然后在布局文件中引用就可以了。 <CheckBox android:id="@+id/cb1" android:layout_width="match_parent" android:layout_height="wrap_content" android:button="@drawable/checkboxstyle" android:text="@string/checkbox1" /> 3.6 Radiobutton Radiobutton类官方文档地址:http://developer.android.com/reference/android/widget/RadioButton.html RadioButton与CheckBox监听步骤类似,但RadioButton监听需要注意三点: 1.RadioButton与CheckBox使用的监听器不同。 2.RadioButton绑定监听的时候,不是每个RadioButton都去绑定,因为所有的RadioButton都被放在了RadioGroup单选组中,所以只需要将RadioGroup绑定上监听器即可。 3.重写监听器函数onCheckedChanged(RadioGroup group, int checkedId),这个函数的第一个参数是单选组,注意第二个参数,这里的checkedId不是RadioGroup单选组中的每个RadioButton的下标,而是发生状态改变的RadioButton的内存ID。所以在进行判断哪个RadioButton发生状态改变的时候,可以利用RadioButton.getID来与checkedId进行对比 <?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" > <RadioGroup android:id="@+id/radGrp" android:layout_width="wrap_content" android:layout_height="wrap_content" > <RadioButton android:id="@+id/rb1" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/rb1" /> <RadioButton android:id="@+id/rb2" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/rb2" /> <RadioButton android:id="@+id/rb3" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/rb3" /> </RadioGroup> </LinearLayout> import android.app.Activity; import android.os.Bundle; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.RadioGroup.OnCheckedChangeListener; import android.widget.Toast; public class MainActivity extends Activity implements OnCheckedChangeListener { private RadioButton rb1, rb2, rb3; private RadioGroup rg; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); rb1 = (RadioButton) findViewById(R.id.rb1); rb2 = (RadioButton) findViewById(R.id.rb2); rb3 = (RadioButton) findViewById(R.id.rb3); rg = (RadioGroup) findViewById(R.id.radGrp); rg.setOnCheckedChangeListener(this);// 将单选组绑定监听器 } // 重写监听器函数 /* * onCheckedChanged(RadioGroup group, int checkedId) 第一个参数是单选组 * 第二个参数这里的checkedId发生改变的RadioButton的内存ID。 * 在进行判断哪个RadioButton发生状态改变的时候,可以利用RadioButton.getID来与checkedId进行对比 */ @Override public void onCheckedChanged(RadioGroup group, int checkedId) { if (group == rg) { String rbName = null; if (checkedId == rb1.getId()) { rbName = rb1.getText().toString(); } else if (checkedId == rb2.getId()) { rbName = rb2.getText().toString(); } else if (checkedId == rb3.getId()) { rbName = rb3.getText().toString(); } Toast.makeText(this, "选择了下标为“" + rbName + "”的单选按钮", Toast.LENGTH_SHORT).show(); } } } 本文转自叶超Luka博客园博客,原文链接:http://www.cnblogs.com/yc-755909659/p/3737949.html,如需转载请自行联系原作者

优秀的个人博客,低调大师

【读书笔记《Android游戏编程之从零开始》】3.Android 游戏开发常用的系统控件(Button、Layout、ImageButto...

3.1 Button Button这控件不用多说,就是一个按钮,主要是点击后进行相应事件的响应。 给组件添加ID属性:定义格式为 android:id="@+id/name",这里的name是自定义的,不是索引变量。“@+”表示新声明,"@"表示引用,例如: "@+id/tv" 表示新声明一个id,是id名为tv的组件; "@id/tv" 表示引用id名为tv的组件。 给按钮添加点击事件响应 想知道按钮是否被用户点击,就需要一个“点击监听器”来对其进行监听,然后通过监听器来获取点击的事件,就可以判断关注的按钮是否被用户所点击。 使用监听器有两种方式:1.当前类使用点击监听器接口,修改后源码如下: //使用点击监听器 public class ButtonProject extends Activity implements OnClickListener { private Button btn_submit,btn_cancel; private TextView tv; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.button_project_layout); btn_submit = (Button) findViewById(R.id.btn_submit); btn_cancel = (Button)findViewById(R.id.btn_cancel); tv = (TextView)findViewById(R.id.tv); btn_submit.setOnClickListener(this); btn_cancel.setOnClickListener(this); } //使用点击监听器必须重写其抽象函数, //@Override 表示重写函数 @Override public void onClick(View v) { // TODO Auto-generated method stub if(v == btn_submit) { tv.setText("确定按钮触发事件!"); }else if(v==btn_cancel) { tv.setText("取消按钮触发事件!"); } } } 先用当前类使用点击监听器接口(onClickListner),重写点击监听器的抽象函数(onClick);然后对需要监听的按钮进行按钮绑定监听器操作,这样监听器才能对绑定的按钮进行监听,以判断其是否被用户点击,一旦按钮被点击,就会自动响应onClick函数,并将点击的button(button也是 1个view)传入;最后就可以在onClick函数中书写点击会触发的事件(因为定义了多个按钮,所以在onClick函数中对系统传入的view进行按钮匹配的判断,让不同的按钮做不通的处理事件)。 2.使用内部类实现监听器进行监听,修改后源代码如下: public class ButtonProject extends Activity { private Button btn_submit,btn_cancel; private TextView tv; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.button_project_layout); btn_submit = (Button) findViewById(R.id.btn_submit); btn_cancel = (Button)findViewById(R.id.btn_cancel); tv = (TextView)findViewById(R.id.tv); //将btn_submit按钮绑定点击监听器 btn_submit.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub tv.setText("确定按钮触发事件!"); } }); btn_cancel.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub tv.setText("取消按钮触发事件!"); } }); } } 利用内部类的形式也需要重写监听器的抽象函数,然后在onClick里进行处理事件,这里不用判断view了,因为一个Button对应了一个监听器。 Button类官方文档地址:http://developer.android.com/reference/android/widget/Button.html 其中有说明,如果不用OnClickListener监听器的话,现在可以在XML布局按钮控件中使用android:onClick属性。然后在类中调用你设置的onClick方法。代码如下: <Button android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="@string/self_destruct" android:onClick="selfDestruct" /> 当用户单击按钮时,Android系统调用selfDestruct方法。该方法必须是公开并接受一个视图作为其唯一的参数。 public void selfDestruct(View view) { // 按钮响应事件 } 3.2 Layout 1.线性布局 LinearLayout LinearLayout类官方文档地址:http://developer.android.com/reference/android/widget/LinearLayout.html LinearLayout(线性布局)是5中布局中最常用的一种,此布局在显示组件的时候会默认保持组件的间隔以及组件之间的相互对其(相对一个组件的右对齐、中间对齐或者左对齐)。线性布局显示组件的方式有垂直与水平两种,可以通过orienrarion进行设定。 orientation属性表示设置布局中的控件的方向,其属性值有两种,一种是“vertical”垂直排列(见下图左),另一种是“horizontal”水平排列(见下图右)。 (1)gravity:每个组件默认其值为左上角对齐,其属性可以调整组件对齐方式,比如向左、向右、或者居中对齐等。 (2)padding:边距的填充,也称内边距。其边距属性有: android:paddingTop,设置上边距; android:paddingBottom,设置下边距; android:paddingLeft,设置左边距; android:paddingRight,设置右边距; android:padding则表示周围四方向各内边距统一调整。 边距属性值为具体数字。 (3)layout_margn:外边距,其上下左右边距属性类似内边距。 padding内边距指的是当前布局与包含的组件之间的边距;layout_margn外边距指的是与其他组件之间的边距。 2.相对布局 RelativeLayout RelativeLayout类官方文档地址:http://developer.android.com/reference/android/widget/RelativeLayout.html RelativeLayout(相对布局):除了最常用的LinearLayout之外,相对布局则是另一种常用的布局。与线性布局不同之处在于,线性布局如果需要将一组件对齐另外一个组件就必须将所有的组件进行对齐,或者使用嵌套布局才可以完成;但是相对布局不必这么麻烦。因为在相对布局中,每个组件都可以指定相对于其他组件或父组件的位置,只是必须通过ID来进行指定。修改main.xml布局如下; 所以在相对布局中,如果想固定一个组件的位置,至少要确定组件“左右”与“上下”两个位置才可以准确固定组件的位置。 3.表格布局 TableLayout TableLayout类官方文档地址:http://developer.android.com/reference/android/widget/TableLayout.html Tablelayout(表格布局)的样式如同一个表格。通常情况下,TableLayout有多个TableRow组成,每个TableRow就是一行,定义几个TableRow就是定义几行:TableLayout不会显示行列号,也没有分割线。其行数和列数也是有自己来操作和确定的。 下面来介绍在TableLayout中常用的几个属性: (1)shrinkColumns属性:以0为序,当TableRow里面的控件布满布局时,指定列自动延伸以填充可用部分;当TableRow里面的控件还没有布满布局时,不起作用。 (2)strechColumns属性:以第0行为序,指定列对空白部分进行填充。 (3)collapseColumns属性:以第0行为序,隐藏指定的列。 (4)layout_column属性:以第0行为序,设置组件显示在指定列。 (5)layout_span属性:以第0行为序,设置组件显示占用的列数。 4.绝对布局 AbsoluteLayout AbsoluteLayout类官方文档地址:http://developer.android.com/reference/android/widget/AbsoluteLayout.html AbsoluteLayout(绝对布局)布局用法如其名,组件的位置可以准确的指定其在屏幕的x/y坐标位置。虽然可以精确的去规定坐标,但是由于代码的书写过于刚硬,使在不同的设备,不同分辨率的手机移动设备上不能很好的显示应有的效果,此布局设定组件位置都是用x/y来进行调整,又使得整体布局格式代码很不灵活,所以此布局不推荐使用。 5.单帧布局 FrameLayout FrameLayout类官方文档地址:http://developer.android.com/reference/android/widget/FrameLayout.htm FrameLayout(单帧布局)是5中布局中最简单的一种,因为单帧布局在新定义组件的时候永远都会将组件放在屏幕的左上角,即使在此布局中定义多个组件,后一个组件总会将前一个组件覆盖,除非最后一个组件是透明的。 3.3 ImageButton ImageButton类官方文档地址:http://developer.android.com/reference/android/widget/ImageButton.html ImageButton与Button类似 ,区别在于ImageButton可以自定义一张图片作为一个按钮;也正因为使用图片代替了按钮,所以ImageButton按下与抬起的样式效果需要自定义。 <?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" > <ImageButton android:id="@+id/btn_ImageButton" android:layout_marginLeft="100dp" android:layout_marginTop="100dp" android:layout_width="100dp" android:layout_height="100dp" android:background="@drawable/dsfvsdf" /> </LinearLayout> public class ImageButtonProject extends Activity { private ImageButton btn_ImageButton; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.imagebutton_layout); btn_ImageButton = (ImageButton)findViewById(R.id.btn_ImageButton); //为图片按钮添加触屏监听 btn_ImageButton.setOnTouchListener(new OnTouchListener() { @Override //第一个参数:表示触发触屏事件的事件源view //第二个参数:表示触屏事件的类型,如按下、抬起、移动等。 public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub if(event.getAction()==MotionEvent.ACTION_DOWN)//按下事件 { //设置图片按钮背景 //getResources().getDrawable(int ID) 传入图片ID得到一个Drawable对象。 btn_ImageButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.dsfvsdf_bg)); }else if(event.getAction()==MotionEvent.ACTION_UP)//抬起事件 { btn_ImageButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.dsfvsdf)); } return false; } }); } } 显示不同的按钮状态官方文档中有提到可以在单独在xml文件中配置,然后布局文件中引用就可以了,代码如下: <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="true" android:drawable="@drawable/button_pressed" /> <!-- pressed 按下状态--> <item android:state_focused="true" android:drawable="@drawable/button_focused" /> <!-- focused 聚焦状态--> <item android:drawable="@drawable/button_normal" /> <!-- default 默认状态--> </selector> 本文转自叶超Luka博客园博客,原文链接:http://www.cnblogs.com/yc-755909659/p/3731190.html,如需转载请自行联系原作者

优秀的个人博客,低调大师

Android编程获取手机型号,本机电话号码,sdk版本及firmware版本号(即系统版本号)

Android开发平台中,可通过TelephonyManager获取本机号码。 TelephonyManager phoneMgr=(TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE); txtPhoneNumber.setText(phoneMgr.getLine1Number()); //txtPhoneNumber是一个EditText 用于显示手机号 注: 根据Android的安全机制,在使用TelephonyManager时,必须在AndroidManifest.xml中添加<uses-permission android:name="READ_PHONE_STATE" /> 否则无法获得系统的许可。 手机型号 Build.MODEL String MODEL The end-user-visible name for the end product. sdk版本 Build.VERSION.SDK String SDK This constant is deprecated. UseSDK_INTto easily get this as an integer. 及frimware版本号(系统版本号)Build.VERSION.RELEASE String RELEASE The user-visible version string. 如:2.1-update1 本文转自xyz_lmn51CTO博客,原文链接:http://blog.51cto.com/xyzlmn/818162,如需转载请自行联系原作者

资源下载

更多资源
优质分享App

优质分享App

近一个月的开发和优化,本站点的第一个app全新上线。该app采用极致压缩,本体才4.36MB。系统里面做了大量数据访问、缓存优化。方便用户在手机上查看文章。后续会推出HarmonyOS的适配版本。

Mario

Mario

马里奥是站在游戏界顶峰的超人气多面角色。马里奥靠吃蘑菇成长,特征是大鼻子、头戴帽子、身穿背带裤,还留着胡子。与他的双胞胎兄弟路易基一起,长年担任任天堂的招牌角色。

腾讯云软件源

腾讯云软件源

为解决软件依赖安装时官方源访问速度慢的问题,腾讯云为一些软件搭建了缓存服务。您可以通过使用腾讯云软件源站来提升依赖包的安装速度。为了方便用户自由搭建服务架构,目前腾讯云软件源站支持公网访问和内网访问。

Sublime Text

Sublime Text

Sublime Text具有漂亮的用户界面和强大的功能,例如代码缩略图,Python的插件,代码段等。还可自定义键绑定,菜单和工具栏。Sublime Text 的主要功能包括:拼写检查,书签,完整的 Python API , Goto 功能,即时项目切换,多选择,多窗口等等。Sublime Text 是一个跨平台的编辑器,同时支持Windows、Linux、Mac OS X等操作系统。

用户登录
用户注册
修改密码
忘记密码