EditText是接受用户输入信息的最重要Android UI组件,可以利用EditText.getText()获取它的文本内容。
实例:EditTextDemo
运行效果:
代码清单:
布局文件:main.xml
<?xml version="1.0" encoding="utf-8"?> <TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:stretchColumns="1" > <TableRow> <TextView android:gravity="right" android:textStyle="bold" android:padding="3dip" android:text="用户名称:" /> <EditText android:id="@+id/username" android:padding="3dip" android:scrollHorizontally="true" /> </TableRow> <TableRow> <TextView android:gravity="right" android:textStyle="bold" android:padding="3dip" android:text="用户密码:" /> <EditText android:id="@+id/password" android:padding="3dip" android:password="true" /> </TableRow> <TableRow android:gravity="right"> <Button android:id="@+id/cancel" android:text="取消" /> <Button android:id="@+id/login" android:text="登录" /> </TableRow> </TableLayout>
Java源代码文件:MainActivity.java
package com.rainsong.edittextdemo; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends Activity { Button btn_login; OnClickListener listener_login; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); listener_login = new OnClickListener() { public void onClick(View v) { EditText username = (EditText) findViewById(R.id.username); EditText password = (EditText) findViewById(R.id.password); Toast.makeText(MainActivity.this, "用户名称:" + username.getText() + ", 用户密码:" + password.getText(),Toast.LENGTH_SHORT).show(); } }; btn_login = (Button)findViewById(R.id.login); btn_login.setOnClickListener(listener_login); } }
API知识点
android.widget.EditText
public class
EditText
extends TextView
Known Direct Subclasses
AutoCompleteTextView, ExtractEditText, SearchEditText
Known Indirect Subclasses
MultiAutoCompleteTextView
Class Overview
EditText is a thin veneer over TextView that configures itself to be editable.
Public Constructors
EditText(Context context)
EditText(Context context, AttributeSet attrs)
EditText(Context context, AttributeSet attrs, int defStyleAttr)
EditText(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)
Editable getText()
Return the text the TextView is displaying.
时间: 2024-10-12 19:50:52