Android 从输入框获取信息

activity_main.xml中加入以下代码

1
2
3
4
5
6
7
8
9
10
11
12
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/button"/>

<EditText
android:id="@+id/edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxLines="2"
android:hint="Type something here"/>

接着在MainActivity.java中添加逻辑控制程序
onCreate之前定义ButtonEditText,之后再在onCreate方法下添加代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
private EditText editText;
private Button button;

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

button = (Button)findViewById(R.id.button);
editText = (EditText)findViewById(R.id.edit_text);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.button:
String inputText = editText.getText().toString();
Toast.makeText(MainActivity.this, inputText,Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
});
}

如果直接用EditText editText来定义会报错。

Comments

Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×