带点东西去下个页面
目标人群:没有基础的安卓初学者
知识点:Activity之间的通信、获得输入框中的内容
目标:将主页面输入框内容传递至下一页面中
简介
如何获得某个文字控件的内容
如何将一个页面的变量传递至另一页面
本章需要少量Java语法知识
正文
1.基于上一章的内容,在activity_main.xml中添加一个Edittext控件,添加后的内容如下
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent">
<TextView
android:id="@+id/textView"
android:text="@string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="随便说点什么吧?"
android:id="@+id/editText" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="下一页"
android:onClick="goHello"
android:id="@+id/button" />
</LinearLayout>
- android:hint属性为当输入框内容为空时,输入框内的文字,颜色与正常输入文字颜色有所不同
2.在MainActivity.java中找到goHello方法,得到输入框文字并将文字内容传递至下一页面,代码如下
public void goHello(View view) {
//得到输入框中的文字
EditText editText = (EditText) findViewById(R.id.editText);
String editTxt = editText.getText().toString();
Intent intent = new Intent(this, HelloActivity.class);
//将输入框中的文字传递至下一页面
intent.putExtra("editTxt", editTxt);
startActivity(intent);
}
- 如同注释所示,当按钮被点击时,我们将会得到输入框中的文字,并将其传递至下个页面当中
- intent.putExtrar方法中的两个参数分别表示传递变量的名称和值
- 我们也可以尝试传递其他类型的参数
3.找到HelloActivity.java的文件,向onCreate方法中添加如下代码。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hello);
//得到从上一页面传递过来的文字内容
String editTxt = getIntent().getStringExtra("editTxt");
//将得到的文字内容显示在Textview控件当中
TextView textView = (TextView) findViewById(R.id.textView1);
textView.setText(editTxt);
}
- 我们在onCreate方法中得到了从上一页面传递过来的String变量,并将其显示在Textview控件当中
4.重新Build你的项目,并在模拟器上运行,向输入框中输入一些文字,点击按钮,如可在新页面中看到你所输入的内容,那么恭喜你,完成了本章的内容。