Android doc |Getting Started|部分 部分译文 --Building Your First App

Building a Simple User Interface

Android App的图形用户界面是由一层层的View和ViewGroup对象建立起来的。View对象一般是UI控件(widgets),例如button 或者 text fields.ViewGoup对象是不可见的View容器,它们决定子view是如何布局,比如在一个grid或者一个垂直的list里面。
Android 提供了一个XML表格对应了ViewGroup和view的子类,如此你可以在一个XML使用一个层级的UI元素来定义你的UI。
布局(layouts)都是ViewGroup的子类。在这次的练习,你可以使用LinearLayout。
Tips{
选择性Layouts
Declaring(声明) your UI layout in XML rather than(而不是) runtime code is useful for several reasons, but it’s especially important so you can create different layouts for(适配不同的屏幕) different screen sizes. For example, you can create two versions of a layout and tell the system to use one on “small” screens and the other on “large” screens. For more information, see the class about Supporting Different Devices.
}

LinearLayout is a view group (a subclass of ViewGroup) that lays out child views in either a
线性布局是一个view group指定了子view是以水平还是垂直方向摆放组件。
vertical or horizontal orientation, as specified by the android:orientation attribute. Each child of a
正如android的orientation 属性指定的一样。
LinearLayout appears on the screen in the order in which it appears in the XML.

Two other attributes, android:layout_width and android:layout_height, are required for all views in order to specify(指定) their size.

Because the LinearLayout is the root view in the layout, it should fill the entire(整个) screen area that’s available to the app by setting the width and height to “match_parent”. This value declares that the view should expand its width or height to match the width or height of the parent view.

For more information about layout properties, see the Layout guide.

Note: This string resource has the same name as the element ID: edit_message. However, references to resources are always scoped by the resource type (such as id or string), so using the same name does not cause collisions.(字符串id和抽取的string文字的name一样是OK的)
这里写图片描述
For text in the user interface, always specify(指定) each string as a resource. String resources allow you to manage all UI text in a single location(单一区域), which makes the text easier to find and update. Externalizing(抽取) the strings also allows you to localize(局部化) your app to different languages by providing alternative definitions(提供可选择性的定义) for each string resource.

For more information about using string resources to localize your app for other languages, see the Supporting Different Devices class.(更多国际化相关请参见。。。)

Weight value的作用:
This works fine for the button, but not as well for the text field, because the user might type something longer. It would be nice to fill the unused screen width with the text field. You can do this inside a LinearLayout with the weight property, which you can specify using the android:layout_weight attribute.
这样写对于button是OK的,但是对于text field就不一样了,因为用户可能输入更多的内容。把未使用的屏幕用text field填充会更好。你可以在一个现象布局使用weight属性,你可以这样使用android:layout_weight。

The weight value is a number that specifies the amount of remaining space each view should consume, relative to the amount consumed by sibling views. This works kind of like the amount of ingredients in a drink recipe: “2 parts soda, 1 part syrup” means two-thirds of the drink is soda. For example, if you give one view a weight of 2 and another one a weight of 1, the sum is 3, so the first view fills 2/3 of the remaining space and the second view fills the rest. If you add a third view and give it a weight of 1, then the first view (with weight of 2) now gets 1/2 the remaining space, while the remaining two each get 1/4.
Weight的值是一个数字,它指定了每个控件应该消费的空间。这有点像酒的各个成分:“2份砂,1份糖”意味着2/3的drink是砂。举个例子,如果你一个view的weight是2,另外一个weight是1,那么总数是3,因此,第一个控件填充2/3的空白空间,第二个填充剩下的控件,如果你加了第三个控件,weight是1,then 第一个控件(weight=2)现在占总空间的1/2.而剩余的两个控件各占1/4.
The default weight for all views is 0, so if you specify any weight value greater than 0 to only one view, then that view fills whatever space remains after all views are given the space they require.
所有view的默认weight是0,所以如果你只指定任何比0大的weight值给一个view,那么当所有其他的view被给足他们应该有的空间空,这个view将填充剩余的空间。

Make the Input Box Fill in the Screen Width
In activity_main.xml, modify the so that the attributes look like this:
让Input Box填充屏幕宽度

<EditText android:id="@+id/edit_message"
    android:layout_weight="1"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:hint="@string/edit_message" />

Setting the width to zero (0dp) improves layout performance because using “wrap_content” as the width requires the system to calculate a width that is ultimately irrelevant because the weight value requires another width calculation to fill the remaining space.
设置width熟悉为0改变layout的行为,因为使用 “wrap_content”作为width需要系统计算一个控件的宽度是根本不着边际的因为weight属性需要另一个宽度计算来填充剩余空间。(如果想使用weight属性,先将width置0,个人理解)

========================================================================

Starting Another Activity

Respond to the Send Button
Send按钮的响应

1 In the file res/layout/activity_main.xml, add the android:onClick
attribute to the < Button > element as shown below:

<Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="@string/button_send"
      android:onClick="sendMessage" />

(增加android:onClick=”sendMessage”)

This attribute tells the system to call the sendMessage() method in your activity whenever a user clicks on the button.
该属性告诉系统当用户点击了button调用在Activity里的sendMessage方法

2 In the file java/com.example.myfirstapp/MainActivity.java, add the
sendMessage() method stub as shown below:

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    /** Called when the user clicks the Send button */
    public void sendMessage(View view) {
        // Do something in response to button
    }
}


增加了/* Called when the user clicks the Send button /
public void sendMessage(View view) {
// Do something in response to button
}

In order for the system to match this method to the method name given to android:onClick, the signature must be exactly as shown. Specifically, the method must:
为了让系统匹配android:onClick的方法名,签名必须精确如下所示。尤其是,这个方法必须:(是public的&&空retrun值&&仅有一个View的参数,这个view就是点击的view)

  • Be public
  • Have a void return value
  • Have a View as the only parameter (this will be the View that was
    clicked)

Next, you’ll fill in this method to read the contents of the text field and deliver that text to another activity.

Build an Intent
构建一个Intent(意图)
An Intent is an object that provides runtime binding between separate components (such as two activities). The Intent represents an app’s “intent to do something.” You can use intents for a wide variety of tasks, but in this lesson, your intent starts another activity.
Intent是一个对象,在两个完全分离的组件之间提供运行时绑定(比如两个Activity)这个Intent代表一个app想要做什么。你可以使用Intent去完成各种各样的任务,但在本次课程,你的Intent启动另一个Activity

In MainActivity.java, add the code shown below to sendMessage():
sendMessage方法加一些代码:

public class MainActivity extends AppCompatActivity {
    public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    /** Called when the user clicks the Send button */
    public void sendMessage(View view) {
        Intent intent = new Intent(this, DisplayMessageActivity.class);
        EditText editText = (EditText) findViewById(R.id.edit_message);
        String message = editText.getText().toString();
        intent.putExtra(EXTRA_MESSAGE, message);
        startActivity(intent);
    }
}

Note: Android Studio will display Cannot resolve symbol errors because the code references classes like Intent and EditText that have not been imported. To import these classes, you can either 1) use Android Studio’s “import class” functionality by pressing Alt + Enter (Option + Return on Mac) or 2) manually add import statements at the top of the file.
Note:Android Studio将不会解决由于没有导入相关类(如Intent EditText)的包而引起的符号错误。需要导入这些包,你可以1使用使用Android studio导包功能快捷键Alt+Enter (Option + Return on Mac) 或者2手动导包
There’s a lot going on in sendMessage(), so let’s explain what’s going on.
解释下sendMessage做了什么
The Intent constructor takes two parameters:
Intent的构造方法有两个参数
A Context as its first parameter (this is used because the Activity class is a subclass of Context)
一个Context(上下文)作为第一个参数(这个被使用是因为Activity类是Context的子类)
The Class of the app component to which the system should deliver the Intent (in this case, the activity that should be started).
系统要开启的app组件的类名(在目前的情况,是要开启的Activity)
Note: The reference to DisplayMessageActivity will raise an error in Android Studio because the class doesn’t exist yet. Ignore the error for now; you’ll create the class soon.
Note:指向DisplayMessageActivity的指针将会发出一个error,因为类还没有存在,先忽略它,等会会创建的。

The putExtra() method adds the EditText’s value to the intent. An Intent can carry data types as key-value pairs called extras. Your key is a public constant EXTRA_MESSAGE because the next activity uses the key to retrive the text value. It’s a good practice to define keys for intent extras using your app’s package name as a prefix. This ensures the keys are unique, in case your app interacts with other apps.
putExtra()方法将EditText的值加到了intent里面,一个Intent可以携带叫做extras的键值对形式的数据。你的Key是一个public常量EXTRA_MESSAGE ,下一个Activity将根据这个key获取text的值。用你的app包名作为Intent extras的前缀是一个很好的习惯。在你的应用程序与其他应用程序交互的情况下,这确保keys是惟一的。

The startActivity() method starts an instance of the DisplayMessageActivity specified by the Intent. Now you need to create the class.
startActivity()方法开启了一个DisplayMessageActivity 类的实例,现在创建这个类

Create the Second Activity

  1. In the Project window, right-click the app folder and select New >
    Activity > Empty Activity.
  2. In the Configure Activity window, enter “DisplayMessageActivity” for
    Activity Name and click Finish

Android Studio automatically does three things:

  • Creates the class DisplayMessageActivity.java with an implementation of the required onCreate() method.
  • Creates the corresponding layout file activity_display_message.xml
  • Adds the required element in AndroidManifest.xml.

If you run the app and click the Send button on the first activity, the second activity starts but is empty. This is because the second activity uses the default empty layout provided by the template

Display the Message
Now you will modify the second activity to display the message that was passed by the first activity.
下面定义第二个Activity显示第一个Activity传过来的message
In DisplayMessageActivity.java, add the following code to the onCreate() method:

@Override
protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_display_message);

   Intent intent = getIntent();
   String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
   TextView textView = new TextView(this);
   textView.setTextSize(40);
   textView.setText(message);

   ViewGroup layout = (ViewGroup) findViewById(R.id.activity_display_message);
   layout.addView(textView);
}

Press Alt + Enter (option + return on Mac) to import missing classes.
There’s a lot going on here, so let’s explain:
按Alt+Enter(Mac 上option + return)导包,解释下:

  1. The call getIntent() grabs the intent that started the activity.Every Activity is invoked by an Intent, regardless of how the user navigated there. The call getStringExtra() retrieves the data from the first activity.
  2. You programmatically create a TextView and set its size and message.
  3. You add the TextView to the layout identified by R.id.activity_display_message. You cast the layout to ViewGroup because it is the superclass of all layouts and contains the addView() method.
    1.getIntent方法与开启该Activity的Intent挂钩。不管用户如何操作,每个Activity都是有一个Intent开启的。getStringExtra方法取得了从第一个Activity传递来的数据
    2.以编码方式动态添加TextView并设置大小和显示内容
    3.将这个TextView添加到一个id是activity_display_message的layout布局。你把layout转型为ViewGroup,因为ViewGroup 是所有layout布局的父类包含addView() 方法。

Note: The XML layout generated by previous versions of Android Studio might not include the android:id attribute. The call findViewById() will fail if the layout does not have the android:id attribute. If this is the case, open activity_display_message.xml and add the attribute android:id=”@+id/activity_display_message” to the layout element.
Note:由之前的Android Studio生成的XML文件不包含Android:id属性,findviewbyid将会报错因为找不到id是activity_display_message的布局,在这种情况,需要手动在activity_display_message.xml添加android:id=”@+id/activity_display_message”到layout元素里。
You can now run the app. When it opens, type a message in the text field, and click Send. The second activity replaces the first one on the screen, showing the message you entered in the first activity.
你现在可以运行app。当他打开,在textview里面输一些东西,点击发送。第二个Activity代替第一个Activity显示出来,并展示第一个activity的message
That’s it, you’ve built your first Android app!
第一个Android app完工!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值