奥巴马家书

Stop Doubting Yourself

不要怀疑自己

If you don’t believe in yourself, nobody will. Success starts in your mind, and if all you’re doing is putting yourself down and predicting failure, it will become a self-fulfilling prophecy. Instead of doubting yourself, think positively. Not only will you be happier and more successful, you’ll spread it to everyone around you.

如果你自己不相信自己,那没人会相信你。成功始于你的头脑,如果你所做的是不断地看遍自己,预言着未来的失败,这就真的会成为现实。与其怀疑自己,不如积极的考虑问题。不仅会让自己更加开心和成功,你还能够感染到周围的人。

Stop Being Negative

不要消极

Now that you’re done doubting yourself, stop doubting others. You don’t like when people are critical of you, so stop being critical of others. Think about how you make other people feel–even if you have good intentions, people don’t like hearing negativity.

现在你不要再怀疑自己了,也别再怀疑身边的人。你不希望被人对你挑剔,那么也不要再去挑剔身边的人。想想你给别人带来的什么样的感受吧——即使出发点是好的,别人也不想听到那么多消极的事情呀。

Stop Being Mean

不要那么刻薄

It’s completely possible to step on someone’s toes without meaning to–it happens all the time. There’s no need topile on by purposefully doing mean things, so make a conscious effort to stop being mean. If someone wrongs you, let it go. There’s no need to seek vengeance unless that’s the type of person you want to be.

无意踩到别人的情况真的有可能会发生——常常会发生。但没必要去处心积虑地做一些不好的事情,所以要有意识地让自己不要那么刻薄。如果有人对你无理地对待,随他们去好了。没必要去报复,除非你也想成为那一类的人。

Stop Wasting Time

不要再浪费时间

I’ve said it before, and I’ll say it again:time is the most valuable resource we have. Don’t waste your time on unproductive things. If you want to explore the world’s dark corners, that’s great. I still associate with people who have not-so-kosher careers, but I don’t hang out with those people at the expense of my own short- and long- termgoals.

虽然之前说过了,但我还想再说一遍:时间是我们拥有的最宝贵的资源,不要把时间浪费在没有意义的事情上面,如果你想探索这个世界的黑暗角落,很好。我也认识一些没哟固定工作的一些自由职业者,但我不会以牺牲自己的短期长期目标为代价和他们出去玩乐。

Stop Making Promises

别再做承诺

Always under-promise and over-deliver. When you make a promise, you’re adding responsibility to your plate that, despite all your best intentions, you may not be able to deliver on. More often than not, your promise is an absolute (i.e. “I promise I’ll always love you”), and only Sith deal in absolutes. Instead of making a promise with your words, simply bethere when people need you, and exceed their expectations with your actions.

总是做承诺,总是做不到。每次做承诺都是不禁给自己添了责任,无论你的出发点有多好,你都不可能完成所有的部分。大部分时候,你的承诺都太过绝对(比如“我发誓我永远爱你”),也只能在绝对环境中才能实现。与其用语言许下承诺,不如在别人需要你的时候出现,然后用行动达到他们的期望吧。

Stop Taking Everything Personally

别把每件事太往心里去

People get offended about the strangest things. Take Kendrick Lamar’s now-infamous verse on “Control” this summer: be called out a list of a dozen rappers he thinks he’s better than (and he’s right). The internet went crazy, and rappers all over the industry rushed to their mics to record a response.

The thins is, all K-Dot said is he’s the best rapper. Everyone took it personally, and that’s exactly what he was going for. The lesson to learn from this is that not everything is about you, and if you’re easily upset, someone will use that to their advantage.

人们会因为一些奇怪的事情感到被侵犯。就拿Kendrick Lamar这个夏天备受争议的歌曲《Control》为例:他在歌词中挑衅了一些他认为比他弱的说唱歌手(的确是这样),一石激起千层浪,整个说唱界的歌手都蜂拥录歌作为回击。

重点在于,所有的人都认为自己是最好的说唱者,每个人都更看重自己,这就是他的目的所在。这件事交给我们的无非就是不是所有的事情都要围着你转,如果你是玻璃心,有人会利用这一点。

Just Stop, and Breathe

停一下,深呼吸吧

No matter what you’re doing in life or how your day is going, there’s always room to just stop for a moment and just breathe. Try it right now to celebrate getting through this list of everything you’re doing wrong.

无论你现在在干什么,这一天过得怎么样,你都需要好好停一下深呼吸。不如现在就歇一歇,犒赏自己总算挺过了一些错事。

Bill Gates in His Boyhood

As a child–and as an adult as well–Bill was untidy. It has been said that in order to break of this habit, his mother Mary drew up weekly clothing plans for him. On Mondays he might go to school in blue, on Tuesdays in green, on Wednesdays in brown, on Thursdays in black, and so on. He never did his own laundry. Weekend meal schedules were also planned in detail, lest he should starve.

Dinner table discussions in the Gate’s family were always lively and educational. “It was a rich environment in which to learn,” Bill remembered.

At four, Bill was able to do some simple calculations, such as subtracting and multiplying numbers. Bill’s contemporaries, even at the age, recognized that he was a genius. Every year, he and his friends would go to summer camp. Bill especially liked swimming and other sports. One of his summer camp friends recalled, “He was never the kind of kid you didn’t want your team to have. We all knew Bill was smarter than us. Even back then, when he was nine or ten years old, he talked like an adult and could express himself in ways that none of us understood.”

Bill distinguished himself as a boy who had the marvelous faculty to learn things quickly. He strictly followed the honor code. He was also well ahead of his peers in mathematics and science. He enjoyed debating new ideas and fresh concepts with his classmates. He derived much pleasure from studies. His father, a retired officer, was convinced that he needed to go to a school that challenged him, then his parents sent him to Lakeside–an all-boys’ private school for exceptional students. It was Seattle’s most exclusive secondary school with a great reputation and was noted for its rigorous academic demands and discipline, a place where “even the dumb kids were smart”.

Lakeside allowed students to pursue their own interests, to whatever extent they wished. The school enjoyed a fine reputation and prided itself in furnishing conditions and facilities that would enable all its students to reach their full potential. It was the ideal environment to stimulate the growth of someone like Bill Gates, whose academic performance exceeded his tutors and parents’ wildest expectations.

In 1968, the school made a decision that had changed thirteen-year-old Bill Gates’ life–and that of many of others, too.

Funds were raised, mainly by parents, that enabled the school to gain access to a computer–a Program Data Processor(PDP)–through a teletype machine.

Type in a few instructions on the teletype machine and a few seconds later the PDP would type back its response. Bill Gates immediately liked it–so did his best friend at the time, Kent Evans, and another student, Paul Allen, who was two years older than Bill.

Whenever they had free time, and sometimes when they didn’t, they would dash over to the computer room to use the machine. The students became so single-minded that they soon overtook their teachers in knowledge about computing and got into a lot of trouble because of their strong interest in computers. They were neglecting their other studies–every piece of work was handed in late. Classes were cut. Computer time was also proving to be very expensive. Within months, the whole budget that had been set aside for the year had been used up.

At fourteen, Bill, in conjunction with his friends, was already writing short programs for the computer to perform. Early game programs such as Tic-Tac-Toe, or Noughts and Crosse, and Lunar Landing were written in what was to become Bill’s second language, BASIC.

One of the reasons Bill was so good at programming is because it is mathematical and logical. During his time at Lakeside, Bill scored a perfect eight hundred on a mathematics test. It was extremely important to him to get this grade–he had to take the test more than once in order to do it.

If Bill Gates was going to be good at something, it was essential to be the best.

Bill’s and Paul’s keen interest in computers and the business world meant that they read a great deal. Paul enjoyed magazines like Popular Electronics whereas Bill liked reading business publications. Computer time was expensive and, because both boys were desperate to get more time and because Bill already had an insight into what they could achieve financially, the two of them decided to set themselves up as a company The Lakeside Programmers Group to sell copyrighted softwares of international standards. “Let’s call the real world and try to sell something to it!” Bill announced.

Up 2

Intel chairman Andy Grove has decided to cut the Gordian knot of controversy surrounding stem cell research by simply writing a check.

The check, which he pledged last week, could be for as much as $5 million, depending on how many donors make gifts of between $50,000 and $500,000, which he has promised to match. It will be made out to the University of California-San Francisco(UCSF).

Thanks in part to such private donations, university research into uses for human stem cells–the cells at the earliest stages of development that can form any body part–will continue in California. With private financial support, the state will be less likely to lose talented scientists who would be tempted to leave the field or even leave the country as research dependent on federal money slows to glacial pace.

Hindered by limits President Bush placed on stem cell research a year ago, scientists are turning to laboratories that can carry out work without using federal money. This is awkward for universities, which must spend extra money building separate labs and keeping rigorous records proving no federal funds were involved. Grove’s donation, a first step toward a $20 million target at UCSF, will ease the burden.

The president’s decision a year ago to allow research on already existing stem cell lines was portrayed as a reasonable compromise between scientists’ needs for cells to work with, and concerns that this kind of research could lead to wholesale creation and destruction of human embryos, cloned infants and a general contempt for human life.

But Bush’s effort to please both sides ended up pleasing neither. And it certainly didn’t provide the basis for cutting edge research. Of the 78 existing stem cell lines which Bush said are all that science would ever need, only one is in this country (at the University of Wisconsin) and only five are ready for distribution to researchers. All were grown in conjunction with mouse cells, making future therapeutic uses unlikely.

The Bush administration seems bent on satisfying the small but vocal group of Americans who oppose stem cell research under any conditions. Fortunately, Grove and others are more interested in advancing scientific research that could benefit the large number of Americans who suffer from Parkinson’s disease, nerve injuries, heart diseases and many other problems.

Exchange Activity

A: Good evening, Mr. Karl.
B: Good evening, Miss Bai. Please come in.
A: Thank you. Mr. Karl, tomorrow is the weekend, there will be a dance party. Would you like to join us?
B: Thank you, I’d like to. But I am a poor dancer, I think it’s a good chance for me to learn from you.
A: You must be kidding. I heard you are skilled in dancing. I just look forward to your perfect performance.
B: You flatter me. When will it start?
A: At 7:00 in the evening. This is your Dance Invitation. At 7:00 in the evening, go to the dance hall. Good bye and see you tomorrow evening.
B: OK, see you tomorrow evening at the dance party.


A: Miss Bai, now the music is going on, will you accept my arm?
B: With pleasure. Mr. Karl, I suppose you dance often.
A: I have not danced for a long time.
B: Really? Still you dance wonderfully.
A: I am glad you say so. You dance well, too. … Are you tired?
B: I’m OK, but I feel a little thirsty.
A: Let’s have a rest and get some drinks.
B: OK.

Proposing a Toast

A: Well, ladies and gentlemen, welcome to our party. It is my great pleasure to host this Luncheon in our guests’ honor. Let me propose a toast to our guest! To your health and success in your work.
B: Thank you very much. Cheers!
A: I’d also like to propose a toast to the health of our friends here. Cheers!
C: Cheers! Thank you.
B: Thank you for your hospitality. I look forward to sharing experience and exchanging views with my Chinese colleagues in the coming days.


A: Beloved ladies, gentlemen and friends, friends, first of all, let me be on behalf of our company to extend a warm welcome to the members of the American Delegation who have been invited to this country by this company.
B: Thank you. It is a special honor to me to have a chance to speak on behalf of all the members of our delegation. I would like to express our sincere thanks to president Gao for inviting us, and for all the hard work and thought you have given to the arrangements for our visit. We are so thankful for such a marvelous dinner tonight.
A: We really appreciate Mr. Smith’s effort in coming to Shanghai to talk about the feasibility of a joint venture. We look forward to the success of our mutual collaboration.
B: Well begun is half done, as we say. I hope this visit will pave for further business relations between our two companies.
A: Now, please join me in toasting to the health of Mr. Smith, to everybody else present, to the success of our relationship. Cheers!

Entertaining Customers

A: Mr. Karl, do you have any plans for tomorrow evening?
B: No, I have nothing planned.
A: If it’s convenient for you, I’d like to invite you to a dinner party at the restaurant of the Nan Jiang Hotel. We hope you’ll be able to attend.
B: It’s very kind of you. Thank you for your invitation. When will the dinner begin?
A: The reception will be held at 7:00 p.m. This is your invitation card, Mr. Karl.
B: Thank you. I’ll be delighted to come on time.
A: We sincerely hope you can attend. I’ll pick you up at 6:00 p.m.
B: Thank you. See you tomorrow evening.


A: We’re so happy you’re here today, Mr. Karl.
B: Thank you very much for preparing such a splendid dinner especially for me.
A: It’s our honor to have you come. Dinner is ready, please go to the table.
B: I really do not deserve your kindness. Maybe we could have more talks about the business. When will I hear from you on this?
A: I think I will know something in a day or two.
B: I’m looking forward to this. Hmm, the food is really good here.
A: I’m glad you like it. Thank you for your helping us with marketing development.
B: My pleasure. I hope we could hammer out a deal.

Visiting a Factory

A: Hi, Mr. Karl, welcome to the May Trading Company. How’s everything?
B: Fine. What’s new about you, Mr. Su?
A: Nothing special. Mr. Karl, I’ll show you around the company today. This is the visiting brochure.
B: Where shall we go first?
A: Maybe we could start with the Designing Department, then we could look at the production line. I suggest we start at the beginning of our production line, so you can get a good idea of how things work. After that, I’ll take you to our showroom to explain all the exhibits there.
B: That’s terrific.
A: You’ll have to wear this hard hat during the tour for security.
B: That’s very thoughtful of you.
A: Shall we start on our tour right now? Please come this way.


A: Mr. Karl, on behalf of all our employees, welcome to our company.
B: Thank you. I hope my visit doesn’t cause you too much trouble.
A: Of course not. You’re our expected guest. Which department would you like to visit first?
B: Would it be possible to have a closer look at your Designing Department?
A: OK. This way, please. I’ll show you around the department and explain all the procedures here.
B: Now I know how you did such imaginative designing. Your Designing Department deserves the reputation it enjoys!
A: Thank you. But we still have a long way to go.
B: You are too humble. By the way, may I look at your production line? What kind of quality control do you have?
A: OK, this way please. Mr. Karl, just as you see, all the products need to pass strict inspection before they go out. How about a coffee break?
B: OK, I feel a little tired.

Android中View的Draw

View中:

  1. Draw the background 绘制背景
  2. If necessary, save the canvas’ layers to prepare for fading. 如有必要,颜色渐变淡之前保存画布层(即锁定原有的画布内容)
  3. Draw view’s content. 绘制view的内容
  4. Draw children. 绘制子view
  5. If necessary,draw the fading edges and restore layers. 如有必要,绘制颜色渐变淡的边框,并恢复画布(即画布改变的内容附加到原有内容上)
  6. Draw decorations (scrollbars for instance). 绘制装饰,比如滚动条
public void draw(Canvas canvas){
    ...
    if(!dirtyOpaque){
        drawBackground(canvas);//背景绘制
    }
    // skip step 2 & 5 if possible (common case) 通常情况跳过第2和第5步
    ...
    if(!dirtyQpaque) onDraw(canvas); // 调用onDraw
    dispatchDraw(canvas); // 绘制子view
    onDrawScrollBars(canvas); // 绘制滚动条
    ...
}

protected void dispatchDraw(Canvas canvas){// 空实现}

protected void onDraw(Canvas canvas){// 空实现}

ViewGroup中:

protected void dispatchDraw(Canvas canvas){
    ...
    drawChild(...); // 绘制子View
    ...
}

protected boolean drawChild(Canvas canvas, View child, long drawingTime){
    return child.draw(canvas, this, drawingTime);
}

说明:

  1. 自定义一个View时,重写onDraw。
    调用view.invalidate(), 会触发onDraw和computeScroll(). 前提是该View被附加在当前窗口
    view.postInvalidate();//是在非UI线程上调用的

  2. 自定义一个ViewGroup,重写onDraw。
    onDraw可能不会被调用,原因是需要先设置一个背景(颜色或图)
    表示这个group有东西需要绘制了,才会触发draw,之后是onDraw。
    因此,一般直接重写dispatchDraw来绘制viewGroup

  3. 自定义一个ViewGroup
    dispatchDraw会调用drawChild。

英语单词state和status的区别

state:比较常用,各种状态都可以用它,但是它更着重于一种心理状态或者物理状态。
Status:用在人的身上一般是其身份和地位,作“状态,情形”讲时,多指政治和商业。

state倾向于condition,是一种延续性的状态。status常用于描述一个过程中的某阶段(phase),类似于C语言中枚举型变量某一个固定的值,这个值属于一个已知的集合。
比如淘宝买家问卖家“我的网购现在是什么状况?”
这个问题的背景是讲话双方都清楚,交易状态有“买家选购”“买家已付款”“卖家已发货”“买家已签收”或者有“买家已
投诉”等等状态。这些状态描述一件事情发展过程中的不同阶段。而且,这些阶段的先后顺序也是双方默许的。
所以在这里可以问“What’s the status of my purchase?”,此处用state不太贴切,如果硬用上去从语感上可能听着别扭。

说物态变化用state再恰当不过。如果说一个物质的四种状态,可以说“solid state”,但如果你说“solid status”,第
一,这两个词的组合不像是描述物态,更像是在说“确定的状况(solid产生歧义‘确定的/确凿的’)”;第二,这个说法即
使不被误解,也需要事先约定一组物态变化顺序,比如把这个物质从固态开始加热然后电离,可能先后经历固态、液态、气态、等离子态这四个阶段。类似先定义枚举,然后引用的方式。

扩展:
ajax中readyState,statusText,onreadystatechange,window.status怎么一会state一会是status都晕乎了

state所指的状态,一般都是有限的、可列举的,status则是不可确定的。
比如
readyState — 就那么四五种值
statusText — 描述性的文字,可以任意
onreadystatechange — 那么四五种值之间发生变化
window.status — 描述性的文字,可以任意

来个形象的比方,你体重多少公斤,属于status,但说你体重属于偏瘦、正常还是偏胖,那就是state.

Up 1

It used to be that people were proud(自豪) to work for the same company(同伴) for the whole of their working lives. They’d get a gold watch at the end of their productive(多产的,富饶的) years and a dinner featuring(容貌,特色) speeches by their bosses praising their loyalty(忠诚). But today’s rich capitalists(资本家,有钱人) have regressed(退步) to the “survival of the fittest” ideas and their loyalty extends not to their workers or even to their stockholders but only to themselves. Instead of giving out gold watches worth a hundred or so dollars for forty or so years of work, they grab tens and even hundreds of millions of dollars as they sell for their own profit the company they may have been with for only a few years.

The new rich selfishly act on their own to unfairly grab the wealth that the country as a whole has produced. The top 1 percent of the population now has wealth equal to the whole bottom 95 percent and they want more. Their selfishness is most shamelessly expressed in downsizing and outsourcing because these business maneuvers don’t act to create new jobs as the founders of new industries used to do, but only to cut out jobs while keeping the money value of what those jobs produced for themselves.

To keep the money machine working smoothly the rich have bought all the politicians from the top down. The president himself is constantly leaving Washington and the business of the nation because he is summoned to “fundraising dinners” where fat cats pay a thousand or so dollars a plate to worm their way into government not through service but through donations of vast amounts of money. Once on the inside they have both political parties busily tearing up all the regulations that protect the rest of us from the greed of the rich.

The middle class used to be loyal to the free enterprise system. In the past, the people of the middle class mostly thought they’d be rich themselves someday or have a good shot at becoming rich. But nowadays income is being distributed more and more unevenly and corporate loyalty is a thing of the past. The middle class may also wake up to forget its loyalty to the so-called free enterprise system altogether and the government which governs only the rest of us while letting the corporations do what they please with our jobs. As things stand, if somebody doesn’t wake up, the middle class is on a path to being downsized all the way to the bottom of society.

The King’s Four Wives

Once upon a time there was a rich king who had four wives in a flourishing kingdom. He loved his fourth wife the most and adorned her with riches. He also loved his third wife and was always showing her off to neighboring kingdoms. However, he always feared that she would leave him. His second wife was kind and considerate and he trusted this female friend and advisor in difficult times. Wife number one was devoted and loyal and although she loved him deeply, he was not so interested and tended to ignore her.

One day, the king fell ill with cancer; despite the diverse therapies he received and the many vitamins and medicinal compounds he took at regular intervals to supplement his daily diet, the invisible virus of the disease had invaded the vital organs in his body and all efforts to restore his health had failed. The king reckoned he was doomed. He thought of his luxurious life and feared being alone when he died. He removed the crown from his head and asked his fourth wife in a most serious tone, “I have loved you the most and provided you with the finest clothing and showered great care over you. Now that I’m dying, will you follow me and keep me company?” “No way!” she replied and walked away without another word. The sad king then asked the third wife, “I have loved you all my life. Now that I’m dying, will you follow me and keep me company?” “No!” she replied. “Life is too good! When you die, I’m going to remarry!”

He then asked the second wife, “I have always turned to you for help and you’ve always been there for me. When I die, will you follow me and keep me company? “I’m sorry, I can’t help you out this time!” she replied. “At the very most, I can help with your funeral.”

Then a voice called out to the king in his sadness: “I’ll leave with you and follow you no matter where you go.” The king looked up and there was his first wife who was kneeling down. She was so skinny and undernourished. Greatly grieved, the king said, “I should have taken much better care of you when I had the chance!”

In truth, we all have four wives in our lives. Our fourth wife is our body. No matter how much time and effort we use in making it look good, it’ll leave us when we die. Our third wife is our possessions, status and wealth. When we die, it’ll all go to others. Our second wife is our family and friends. No matter how much they have been there for us, the furthest they can stay by us is up to the grave. And our first wife is our soul, often neglected in pursuit of wealth, power and pleasure. However, our soul is the only thing that will follow us wherever we go.

The moral: Look after after your body and keep it healthy so you can live life to its fullest. Enjoy your possessions and the comfort they provide. Cherish your friends and family and the love they provide. But don’t forget to nourish your soul–it is the source of all your most faithful friend.

Company Profile

A: Can you tell me something about your company?
B: Yes. Our company was set up in 1983 with a capital of 1 million yuan. It’s now one of the biggest domestic trading companies, and we have offices in every major city. The annual output value reached 200 million yuan last year.
A: Great. How many emplayees do you have?
B: There are about 1,500 in the factory and 300 in the office.
A: What is you market share?
B: We now have 30% of the market. We will get more next year as our new production line is put into operation.
A: I heard that you are expanding your plant.
B: Yes, that will help to develop and speed things up.


A: Mr. Karl, let me introduce our company to you.
B: Oh, thank you, that’s what I am interested in.
A: Our three guiding principles are “customer satisfaction, individual’s dignity and shareholders’ value.”
B: They are indeed important.
A: We pay attention to the training of the employees. Our corporate culture and spirit is the most important.
B: Yes, only when they really grasp the essence of the corporate culture and spirit can the new staff fit into the company and do their jobs well.
A: We also emphasize their expertise and practical skills training. In addition, we have made investment to build the “Experience Service Center”. It is an important bridge between our company and our consumers.
B: That’s interesting. Can you detail it?
A: Before answering this question, I’d like to show you a 20-minute film about this. I think it will be useful for me to give you a more clear explanation.

Accommodation and Arrangement

A: Here we are at the hotel you’re going to stay, Mr. Karl.
B: It looks very beautiful.
A: It’s one of the best hotels in Beijing. This hotel has very good service. You may use the fitting room, swimming pool, sauna, and the massage parlor in this hotel.
B: Sounds nice, thank you very much.
A: This is your room, How do you like this suit?
B: It’s very good, I’m satisfied with everything.
A: I’m glad you like it. You’ll certainly need a good rest after such a long flight. I’ve arranged your schedule. I hope it’s suitable.
B: No problem. Thank you very much for all the considerate arrangements made for me.


A: Here we are, Mr. Karl. Let me help you with the formalities at the front desk.
B: It’s very nice of you.
A: Mr. Karl, We have a tight schedule for your short stay. I hope you don’t mind.
B: It doesn’t matter.
A: I’ll take you to our head office tomorrow. What time shall I come for you?
B: May be 7:30 a.m. is OK.
A: I’ll be there on time. Please wait in the lobby.
B: OK.
A: Perhaps I should let you rest now. This is my card with my phone number. Please call me if you need anything. Have a good rest.
B: Thank you. See you tomorrow.

Android Studio Mac上常用快捷键

⌃:control
⇧:shift
⌥:alt(option)
⌘:cmd(command)

重构(提取为方法):
option+command+M

全局查找:
shift+command+F

搜索并替换:
command+R

大小写切换:
shift+command+U

导包:
option+Enter

全局找文件:
double shift

编译并运行
control+R

删除行:
command+X

全屏:
control+command+F

跳转至第几行:
cmd + L

引入重写父类的方法:
ctr + O

引入接口或抽象类方法的实现:
ctr + I

切换文件:
ctr + tab

局部代码块展开/收缩:
cmd + + / cmd + –

全部代码块展开/收缩:
sft + cmd + + / sft + cmd + –

类名/方法名/变量名 重命名操作:
sft + fn + F6

方法重构,方法抽离:
opt + cmd + M

抽离成方法参数:
opt + cmd + P

抽离为局部变量:
opt + cmd + V

抽离为成员变量:
opt + cmd + F

Android Studio代码行数统计插件Statistics

Android Studio 是没有提提供统计代码全部行数的功能的,但是对于开发者来说,这个功能确实必备的,Statistic统计代码行数非常方便,也很详细。

首先肯定是将插件下载下来,下载地址:https://plugins.jetbrains.com/plugin/4509

也可以直接从插件中搜索

首次安装在AS的View→Tool Windows→Statistic,选择之后会在AS的左下角出现statistic按钮。

一开始里面的内容是空白的,我们点击Refresh,如果还是空白,就点击Settings来添加需要统计行数的项目。

Android Stduio 统计代码行数

android studio统计项目的代码行数的步骤如下:
1. 在弹出Find in Path的框中的Text to find输入\n,接着勾选Regular expression(正则表达式),Context选择anywhere,
Scope根据你想要统计的范围进行选择,File mask选择*.java。(在这里统计项目的Java的代码行数)

2. 下图的Useages in generated code是自动生成的代码,上面那个就是项目的代码行数。

View.setWillNotDraw()方法的使用

这个函数更多被在ViewGroup上调用。

View

自定义View中如果重写了onDraw()即自定义了绘制,那么就应该在构造函数中调用view的setWillNotDraw(false),设置该flag标志。其实默认该标志就是false。

ViewGroup

ViewGroup默认情况下,出于性能考虑,会被设置成WILL_NOT_DROW,这样,ondraw就不会被执行了。

如果我们想重写一个viewgroup的ondraw方法,有两种方法:

  1. 构造函数中,给viewgroup设置一个颜色。
  2. 构造函数中,调用setWillNotDraw(false),去掉其WILL_NOT_DRAW flag。

在viewgroup初始化的时候,它调用了一个私有方法:initViewGroup,它里面会有一句setFlags(WILLL_NOT_DRAW,DRAW_MASK);相当于调用了setWillNotDraw(true)
所以说,对于ViewGroup,他就认为是透明的了,如果我们想要重写onDraw,就要调用setWillNotDraw(false)。

试分析-ShimmerFrameLayout

数据结构

public class ShimmerFrameLayout extends FrameLayout{
    // enum specity(特殊) the shape(形状) of the highlight mask applied to the contained view
    // 内容控件高光蒙版效果的枚举
    public enum MaskShape{
        LINEAR, // 线性效果
        RADIAL  // 辐射效果
    }
    // enum controlling the angle of the highlight mask animation
    // 控制高光蒙版动画的角度
    public enum MaskAngel{
        CW_0, // left to right      水平向右划过
        CW_90, // top to bottom     垂直向下落
        CW_180, // right to left    水平向左划过
        CW_270, // bottom to top    垂直向上冲
    }
    // struct storing(存储) various(各种) mask related(相关) parameters, which are used to construct the mask bitmap
    // 存放各种蒙版参数的类结构,这些参数是用于创建蒙版位图
    private static class Mask{
        public MaskAngle angle; // 动画角度
        public float tilt;      // 动画角度偏移
        public float dropoff;   // 掉落??
        public int fixedWidth;  // 固定宽度
        public int fixedHeight; // 固定高度
        public float intensity; // 强度
        public float relativeWidth; // 相对宽度
        public float relativeHeight; // 相对高度
        public MaskShape shape; // 动画形状
    }
    // struct for storing the mask translation animation values
    // 存放蒙版移动动画的起始点信息
    private staic class MaskTranslation{
        public int fromX;
        public int fromY;
        public int toX;
        public int toY;
    }
}

流程步骤

  1. 在构造方法中初始化参数
  2. 启动动画(自动启动或主动调用)
  3. 在动画中刷新参数,并调用invalidate(),触发逻辑
  4. 在dispatchDraw中,使用一个Bitmap结合子控件内容绘制

构造方法

    setWillNotDraw(false);
    mAlphaPaint = new Paint();
    mMaskPaint = new Paint();
    // 初始化
    useDefaults();

    if (attrs != null) {
        // 读取属性
    }

setWillNotDraw

动画

/**
   * Start the shimmer animation. If the 'auto start' property is set, this method is called automatically when the
   * layout is attached to the current window. Calling this method has no effect if the animation is already playing.
   * 如果设置为自动开启动画(auto start),这个方法当绑定到窗口之后就会自动调用
   */
  public void startShimmerAnimation() {
    if (mAnimationStarted) {
      return;
    }
    Animator animator = getShimmerAnimation();
    animator.start();
    mAnimationStarted = true;
  }

  /**
   * Stop the shimmer animation. Calling this method has no effect if the animation hasn't been started yet.
   */
  public void stopShimmerAnimation() {
    if (mAnimator != null) {
      mAnimator.end();
      mAnimator.removeAllUpdateListeners();
      mAnimator.cancel();
    }
    mAnimator = null;
    mAnimationStarted = false;
  }

  @Override
  protected void onAttachedToWindow() {
    super.onAttachedToWindow();
    if (mGlobalLayoutListener == null) {
      mGlobalLayoutListener = getLayoutListener();
    }
    // 绑定到窗口后,等子视图都摆放好后,就会尝试启动动画
    getViewTreeObserver().addOnGlobalLayoutListener(mGlobalLayoutListener);
  }

  private ViewTreeObserver.OnGlobalLayoutListener getLayoutListener() {
    return new ViewTreeObserver.OnGlobalLayoutListener() {
      @Override
      public void onGlobalLayout() {
        boolean animationStarted = mAnimationStarted;
        resetAll();
        if (mAutoStart || animationStarted) {
          startShimmerAnimation();
        }
      }
    };
  }

  @Override
  protected void onDetachedFromWindow() {
    stopShimmerAnimation();
    if (mGlobalLayoutListener != null) {
      getViewTreeObserver().removeGlobalOnLayoutListener(mGlobalLayoutListener);
      mGlobalLayoutListener = null;
    }
    super.onDetachedFromWindow();
  }

动画和绘制

动画改变数据

  // Get the shimmer Animator object, which is responsible(负责的) for driving the highlight mask animation.
  private Animator getShimmerAnimation() {
    if (mAnimator != null) {
      return mAnimator;
    }
    int width = getWidth();
    int height = getHeight();
    switch (mMask.shape) {
      default:
      case LINEAR:
        switch (mMask.angle) {
          default: case CW_0: mMaskTranslation.set(-width, 0, width, 0); break;
          case CW_90: mMaskTranslation.set(0, -height, 0, height); break;
          case CW_180: mMaskTranslation.set(width, 0, -width, 0); break;
          case CW_270: mMaskTranslation.set(0, height, 0, -height); break;
        }
    }
    mAnimator = ValueAnimator.ofFloat(0.0f, 1.0f + (float) mRepeatDelay / mDuration);
    mAnimator.setDuration(mDuration + mRepeatDelay);
    mAnimator.setRepeatCount(mRepeatCount);
    mAnimator.setRepeatMode(mRepeatMode);
    mAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
      @Override
      public void onAnimationUpdate(ValueAnimator animation) {
        float value = Math.max(0.0f, Math.min(1.0f, (Float) animation.getAnimatedValue()));
        setMaskOffsetX((int) (mMaskTranslation.fromX * (1 - value) + mMaskTranslation.toX * value));
        setMaskOffsetY((int) (mMaskTranslation.fromY * (1 - value) + mMaskTranslation.toY * value));
      }
    });
    return mAnimator;
  }

  /**
   * Translate the mask offset horizontally. Used by the animator.
   *
   * @param maskOffsetX Horizontal translation offset of the mask
   */
  private void setMaskOffsetX(int maskOffsetX) {
    if (mMaskOffsetX == maskOffsetX) {
      return;
    }
    mMaskOffsetX = maskOffsetX;
    invalidate(); // 使其重绘
  }

  /**
   * Translate the mask offset vertically. Used by the animator.
   *
   * @param maskOffsetY Vertical translation offset of the mask
   */
  private void setMaskOffsetY(int maskOffsetY) {
    if (mMaskOffsetY == maskOffsetY) {
      return;
    }
    mMaskOffsetY = maskOffsetY;
    invalidate(); // 使其重绘
  }

在dispatchDraw处理绘制工作

@Override
  protected void dispatchDraw(Canvas canvas) {
    if (!mAnimationStarted || getWidth() <= 0 || getHeight() <= 0) {
      super.dispatchDraw(canvas);
      return;
    }
    dispatchDrawUsingBitmap(canvas);
  }

  /**
   * Draws and masks the children using a Bitmap.
   *
   * @param canvas Canvas that the masked children will end up being drawn to.
   */
  private boolean dispatchDrawUsingBitmap(Canvas canvas) {
    Bitmap unmaskBitmap = tryObtainRenderUnmaskBitmap();
    Bitmap maskBitmap = tryObtainRenderMaskBitmap();
    if (unmaskBitmap == null || maskBitmap == null) {
      return false;
    }
    // First draw a desaturated version
    drawUnmasked(new Canvas(unmaskBitmap));
    canvas.drawBitmap(unmaskBitmap, 0, 0, mAlphaPaint);

    // Then draw the masked version
    drawMasked(new Canvas(maskBitmap));
    canvas.drawBitmap(maskBitmap, 0, 0, null);

    return true;
  }

最主要的是对Bitmap的处理

/**
   * Draws and masks the children using a Bitmap.
   *
   * @param canvas Canvas that the masked children will end up being drawn to.
   */
  private boolean dispatchDrawUsingBitmap(Canvas canvas) {
    Bitmap unmaskBitmap = tryObtainRenderUnmaskBitmap();    // 获取一个Bitmap,
    Bitmap maskBitmap = tryObtainRenderMaskBitmap();        // 获取一个Bitmap,
    if (unmaskBitmap == null || maskBitmap == null) {
      return false;
    }
    // First draw a desaturated version
    drawUnmasked(new Canvas(unmaskBitmap));     // 将子控件绘制到临时的画布上
    canvas.drawBitmap(unmaskBitmap, 0, 0, mAlphaPaint);// 将子控件绘制到屏幕上

    // Then draw the masked version
    drawMasked(new Canvas(maskBitmap));
    canvas.drawBitmap(maskBitmap, 0, 0, null);

    return true;
  }
  // 试图获取一个Bitmap
  private Bitmap tryObtainRenderUnmaskBitmap() {
    if (mRenderUnmaskBitmap == null) {
      mRenderUnmaskBitmap = tryCreateRenderBitmap();
    }
    return mRenderUnmaskBitmap;
  }

  // 试图获取一个Bitmap
  private Bitmap tryObtainRenderMaskBitmap() {
    if (mRenderMaskBitmap == null) {
      mRenderMaskBitmap = tryCreateRenderBitmap();
    }
    return mRenderMaskBitmap;
  }

  // 其实就是创建一个和自己一样大的Bitmap
  private Bitmap tryCreateRenderBitmap() {
    int width = getWidth();
    int height = getHeight();
    try {
      return createBitmapAndGcIfNecessary(width, height);
    } catch (OutOfMemoryError e) {
      // 打印log
      String logMessage = "ShimmerFrameLayout failed to create working bitmap";
      StringBuilder logMessageStringBuilder = new StringBuilder(logMessage);
      logMessageStringBuilder.append(" (width = ");
      logMessageStringBuilder.append(width);
      logMessageStringBuilder.append(", height = ");
      logMessageStringBuilder.append(height);
      logMessageStringBuilder.append(")\n\n");
      for (StackTraceElement stackTraceElement :
          Thread.currentThread().getStackTrace()) {
        logMessageStringBuilder.append(stackTraceElement.toString());
        logMessageStringBuilder.append("\n");
      }
      logMessage = logMessageStringBuilder.toString();
      Log.d(TAG, logMessage);
    }
    return null;
  }

  // Draws the children without any mask.
  // 将子控件绘制到画布上
  private void drawUnmasked(Canvas renderCanvas) {
    renderCanvas.drawColor(0, PorterDuff.Mode.CLEAR);
    super.dispatchDraw(renderCanvas);
  }

  // Draws the children and masks them on the given Canvas.
  private void drawMasked(Canvas renderCanvas) {
    Bitmap maskBitmap = getMaskBitmap();
    if (maskBitmap == null) {
      return;
    }

    renderCanvas.clipRect(
        mMaskOffsetX,
        mMaskOffsetY,
        mMaskOffsetX + maskBitmap.getWidth(),
        mMaskOffsetY + maskBitmap.getHeight());
    renderCanvas.drawColor(0, PorterDuff.Mode.CLEAR);
    super.dispatchDraw(renderCanvas);

    renderCanvas.drawBitmap(maskBitmap, mMaskOffsetX, mMaskOffsetY, mMaskPaint);
  }

  // Return the mask bitmap, creating it if necessary.
  private Bitmap getMaskBitmap() {
    if (mMaskBitmap != null) {
      return mMaskBitmap;
    }

    int width = mMask.maskWidth(getWidth());
    int height = mMask.maskHeight(getHeight());

    mMaskBitmap = createBitmapAndGcIfNecessary(width, height);
    Canvas canvas = new Canvas(mMaskBitmap);
    Shader gradient;
    switch (mMask.shape) {
      default:
      case LINEAR: {
        int x1, y1;
        int x2, y2;
        switch (mMask.angle) {
          default:
          case CW_0:
            x1 = 0;
            y1 = 0;
            x2 = width;
            y2 = 0;
            break;
          case CW_90:
            x1 = 0;
            y1 = 0;
            x2 = 0;
            y2 = height;
            break;
          case CW_180:
            x1 = width;
            y1 = 0;
            x2 = 0;
            y2 = 0;
            break;
          case CW_270:
            x1 = 0;
            y1 = height;
            x2 = 0;
            y2 = 0;
            break;
        }
        gradient =
            new LinearGradient(
                x1, y1,
                x2, y2,
                mMask.getGradientColors(),
                mMask.getGradientPositions(),
                Shader.TileMode.REPEAT);
        break;
      }
      case RADIAL: {
        int x = width / 2;
        int y = height / 2;
        gradient =
            new RadialGradient(
                x,
                y,
                (float) (Math.max(width, height) / Math.sqrt(2)),
                mMask.getGradientColors(),
                mMask.getGradientPositions(),
                Shader.TileMode.REPEAT);
        break;
      }
    }
    canvas.rotate(mMask.tilt, width / 2, height / 2);
    Paint paint = new Paint();
    paint.setShader(gradient);
    // We need to increase the rect size to account for the tilt
    int padding = (int) (Math.sqrt(2) * Math.max(width, height)) / 2;
    canvas.drawRect(-padding, -padding, width + padding, height + padding, paint);

    return mMaskBitmap;
  }

Talking on the Way

A: Get on, please. Mr. Karl.
B: Thank you.
A: Is this your first trip to Beijing?
B: Yes, it’s a long-expected visit. Everything I see here is so striking and fresh.
A: Beijing is very good city, we’ll arrange a series of visiting of visiting for you after the negotiation, I hope you enjoy your stay.
B: I believe I will. How far is it to the hotel?
A: About a forty-minute ride. You might as well take a brief look at the outskirts and the city proper along the way.
B: Look, how many newly-built house are dotted about the fields! Ah, I see a flyover there. I suppose we’ll get into the city center soon.
A: Yes, we are approaching the hotel. I’ll send you to You Yi Hotel, we had a reservation there.


A: Let me put your cases into the boot, and please take your seat.
B: Thanks!
A: Do you feel better now, Mr. Karl?
B: That’s OK. I’ll be all right by tomorrow and ready for business. By the way, how’s business these days?
A: Not bad. But sales are down a little bit due to the financial crisis.
B: I can understand. Do you think it’s a general trend?
A: I am not sure, but I believe things will be improved in our endeavour.
B: So do I. It’s no use wrroying.

Meeting at the Airport

A: Excuse me. Are you Mr. Karl from Future Company?
B: Yes. Are you Mr. Su from May Trading Company?
A: Yes. How do you do, Mr. Karl? Welcome to Beijing.
B: How do you do, Mr. Su? Thank you for meeting me at the airport!
A: My pleasure. I’m delighted to meet you. Did you have a good trip?
B: On the whole, it’s not too bad.
A: It’s a long flight to China, and I think you must be very tired. Let me help you with your luggage.
B: Thank you very much.
A: You are welcome. Is your luggage all here with you?
B: Yes.
A: The car is in the exit. Please walk this way.


A: Excuse me, but are you Mr. Karl from Future Company?
B: Yes, I am.
A: I’m delighted to meet you, Mr. Karl. And allow me to introduce myself. I’m Li Zhe, the secretary of Mr. Su. Our manager meant to come here to meet you in person, but some other business held him back, so he asked me to come here in his place to pick you up.
B: How do you do, Mr. Li?
A: How do you do, Mr. Karl? How was your flight? Was it comfortable?
B: Oh, not very good, I feel a little tired, because it’s a very long trip.
A: I booked a room for you at the Dark Hotel, single, for a week. Let’s go and check in the hotel. Then you can release yourself there.
B: Thank you very much. Nothing would be more comfortable than having a hot bath first.
A: Just take a rest over here, Mr. Karl. Please give me your luggage check and I’ll get them for you.
B: Thank you, here you are.
A: Mr. Karl, Is that everything?
B: Yes, that’s all. I’m all set. We’d better start for the hotel.