1. 程式人生 > >Android 動態新增textView或EditText,並獲取輸入資料

Android 動態新增textView或EditText,並獲取輸入資料

  • 問題引入
    Android開發中往往需要動態建立諾幹個同類控制元件,或對他們設定點選事件或批量獲取他們的值,下面提供我在開發中所使用的一種參考。

  • 動態建立多個textView,這裡描述一個頁面取名為:test.xml,現在在Id為MyTable的控制元件裡插入多個textview控制元件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
android:layout_height="match_parent" android:orientation="vertical">
<ScrollView android:layout_width="match_parent" android:layout_height="match_parent" android:fillViewport="true" android:scrollbars="none" > <HorizontalScrollView
android:id="@+id/scroll_view" android:layout_width="match_parent" android:layout_height="match_parent" android:scrollbarAlwaysDrawHorizontalTrack="false" android:scrollbars="none">
<LinearLayout android:id="@+id/MyTable"
android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginBottom="9dp" android:orientation="vertical" >
</LinearLayout> </HorizontalScrollView> </ScrollView> </LinearLayout>
  • java程式碼建立如下:
LinearLayout mainLinerLayout = (LinearLayout) this.findViewById(R.id.MyTable);
TextView textview=new TextView(this);
textview.setText("你好!");
mainLinerLayout.addView(textview);

同理EditText建立方式一樣,不在贅述。(將TextView替換為EditView即可)

  • 對於動態建立的控制元件是不能通過id進行關聯的,因而想要獲取他的內容相對不易,這裡介紹一下對於動態建立的EditText,如何獲取他的值。
    在建立時對editText設定監聽(TextWatcher),重寫裡面的 三個TextChanged函式,完成你所需要的操作
    ps:因為在動態建立,不同於在xml直接寫的,所以在設定監聽時,會讓你將控制元件設為final,在重寫的函式裡,涉及到的也必須是final型變數,獲取裡面的內容可以存在一個外部final變數中,然後操控外部變數進行讀取資料。
LinearLayout mainLinerLayout = (LinearLayout) this.findViewById(R.id.MyTable);
final int cout=i;//用於監聽定位控制元件
final EditText editText=relativeLayout.findViewById(R.id.edit_num);
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//輸入內容之前你想做什麼
                }

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//輸入的時候你想做什麼
                }

@Override
public void afterTextChanged(Editable s) {
    //輸入之後你想做什麼                num[cout]=Integer.parseInt(editText.getText().toString());
                }
            });
mainLinerLayout.addView(editText);

同理對TextView可以設定監聽事件,獲取或設定你的需求。

以上便是我對這方面的理解,歡迎大家提出問題一起討論。