《Android開發卷——實時監聽文字框輸入》
阿新 • • 發佈:2019-02-08
在實際開發中,有時候會讓使用者釋出一些類似微博、說說的東西,但是這個是有限制長度的,除了在文字輸入框限制長度外,還要在旁邊有一條提示還能輸入多少個字的“友好提示”。
1、文字框限制輸入長度
2、安卓沒有提供文字域,這裡順便提一下如果把textview製作成文字域。
<EditText android:id="@+id/push_edit" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#FFFFFF" android:hint="請輸入你要發表的說說內容" android:maxLength="100" android:maxLines="6" android:minLines="6" android:textColor="#6C6C6C" android:textSize="12dp" > <requestFocus /> </EditText>
監聽程式碼
public class MainActivity extends Activity { private EditText pushEdit; private TextView textNum; private Button btnSave,btnDelete; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); pushEdit = (EditText)findViewById(R.id.push_edit); textNum = (TextView)findViewById(R.id.talk_personal_draftbox_num); btnSave = (Button)findViewById(R.id.push_ok); btnDelete = (Button)findViewById(R.id.push_delete); pushEdit.addTextChangedListener(textChange); btnSave.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getBaseContext(), "您提交的內容是:"+pushEdit.getText().toString(), Toast.LENGTH_LONG).show(); } }); btnDelete.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { pushEdit.setText(""); } }); } TextWatcher textChange = new TextWatcher(){ @Override public void afterTextChanged(Editable s) { if(pushEdit.length()<=100){ textNum.setText(100-pushEdit.length()+""); } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { }}; }
專案原始碼:http://download.csdn.net/detail/chillax_li/6920963
尊重原創,轉載請註明出處:http://blog.csdn.net/chillax_li/article/details/19177391