2012-04-12 3 views
7

Моя рабочая среда Eclipse, heliose, Android 1.6Как добавить editText.addTextChangedListener в TableLayout

Я создал TableLayout с колоннами и рядами успешно добавлен, каждая клетка имеет одну TextView и один EditText и у меня есть проблемы в доступ к каждой ячейке и необходимость добавления addTextChangedListener в каждый editText внутри ячейки. Так что мне нужно изменить текст на английский текст. Пожалуйста, предложите решение

/** 
* Here we are going to define the grid The Grid has 1. grid's value in the 
* particular position 2. 
*/ 

public void setGrid() { 

    String questionNumber[] = null; 

    Typeface fontface = Typeface.createFromAsset(getAssets(), "fonts/padmaa.ttf"); 
    /* 
    * Table layout for the crossword elements 
    */ 
    TableLayout tableLayout = (TableLayout) findViewById(R.id.crosswordTableLayout); 
    tableLayout.setGravity(Gravity.TOP); 
    tableLayout.setBackgroundColor(Color.WHITE); 
    tableLayout.setScrollContainer(true); 

    for (int i = 0; i < sizeOfGrid; i++) { 
     /* 
     * This table row params is used to set the layout params alone we 
     * are not going to use this anywhere 
     */ 
     TableRow.LayoutParams tableRowParams = new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
     tableRowParams.setMargins(1, 1, 1, 1); 
     tableRowParams.height = 30; 
     tableRowParams.gravity = Gravity.TOP; 

     /* 
     * Defining the row element for the crossword 
     */ 
     TableRow tableRow = new TableRow(this); 
     tableRow.setBackgroundColor(Color.WHITE); 
     tableRow.setPadding(1, 0, 0, 0); 
     tableRow.setGravity(Gravity.TOP); 
     tableRow.setLayoutParams(tableRowParams); 

     for (int j = 0; j < sizeOfGrid; j++) { 

      /* 
      * (1).Here we are defining headerTextView to set the clue 
      * numbers. 
      * 2).columnEditText = a edit text view used to get the user 
      * i/p data 
      */ 
      TextView headerTextView = new TextView(this); 
      columnEditText = new EditText(this); 

      headerTextView.setGravity(Gravity.TOP); 
      headerTextView.setTextSize(10); 
      headerTextView.setEnabled(false); 
      headerTextView.setHeight(30); 
      headerTextView.setWidth(10); 
      headerTextView.setTextColor(Color.BLACK); 

      /* Override the edittext that has been created */ 
      columnEditText = (EditText) getLayoutInflater().inflate(R.layout.tablexml, null); 
      columnEditText.setHeight(30); 
      columnEditText.setWidth(25); 
      /* 
      * LinearLayout to arrange the two text view in a vertical 
      * position 
      */ 
      LinearLayout headerLinearLayout = new LinearLayout(tableRow.getContext()); 
      headerLinearLayout.setOrientation(LinearLayout.VERTICAL); 
      headerLinearLayout.addView(headerTextView); 

      /* 
      * LinearLayout to arrange the first Linearlayout and Edit text 
      * in a horizontal position 
      */ 
      LinearLayout cellLinearLayout = new LinearLayout(tableRow.getContext()); 
      cellLinearLayout.setOrientation(LinearLayout.HORIZONTAL); 
      cellLinearLayout.addView(headerLinearLayout); 
      cellLinearLayout.addView(columnEditText); 
      /* 
      * Here we are setting the table's vertical border by some 
      * workaround methods 
      */ 
      cellLinearLayout.setLayoutParams(tableRowParams); 
      /* 
      * the column with complete black 
      */ 
      if (cellValueArr[i][j] == null) { 
       columnEditText.setBackgroundColor(Color.BLACK); 
       headerTextView.setBackgroundColor(Color.BLACK); 
       headerTextView.setGravity(Gravity.TOP); 
       tableRow.setBackgroundColor(Color.BLACK); 
       columnEditText.setEnabled(false); 
      } else { 
       /* 
       * column with values and question numbers 
       */ 
       tableRow.setBackgroundColor(Color.BLACK); 
       if (quesNumArr[i][j] == null) { 
        columnEditText.setBackgroundColor(Color.WHITE); 
        headerTextView.setBackgroundColor(Color.WHITE); 
       } else if (quesNumArr[i][j] != null) { 
        /* 
        * column without question number 
        */ 
        questionNumber = quesNumArr[i][j].split("~"); 
        quesArrList.add(questionNumber[1]); 
        headerTextView.setText(questionNumber[1]); 
        headerTextView.setTextColor(Color.BLACK); 
        headerTextView.setBackgroundColor(Color.WHITE); 
        columnEditText.setBackgroundColor(Color.WHITE); 
       } 

      } 
      columnEditText.setId(i); 
      headerTextView.setId(i); 

      /* add the linear layout to the row values */ 
      tableRow.addView(cellLinearLayout); 

      int childCount = tableRow.getChildCount(); 
      System.out.println("Child Count ::" + childCount); 

      LinearLayout linearChild = (LinearLayout) tableRow.getChildAt(columnEditText.getId()); 
      colText = (EditText) linearChild.getChildAt(1); 
      System.out.println("GET ID " + linearChild.getChildAt(1).getId()); 

      colText.addTextChangedListener(new TextWatcher() { 
       @Override 
       public void onTextChanged(CharSequence seq, int start, int before, int count) { 
        // TODO Auto-generated method stub 
        if (seq.length() > 0 & before == 0) { 
         final String charSequence = String.valueOf(seq); 
         final String engChar = String.valueOf(seq.charAt(seq.length() - 1)); 
         println("GUJ :: currentlatin ===> " + engChar + " :: charSequence ==>" + seq); 
         // Method For Type Char 
         List softList = conv.getSoftKeyPressForChar(engChar, getApplicationContext(), seq); 
         charSeq = (String) softList.get(0); 
         Typeface fontface1 = Typeface.createFromAsset(getApplicationContext().getAssets(), "fonts/padmaa.ttf"); 
         colText.setTypeface(fontface1, Typeface.NORMAL); 
         colText.setText(charSeq); 
         // for placing the cursor position 
         colText.clearFocus(); 
         colText.requestFocus(); 

        } 
       } 

       @Override 
       public void beforeTextChanged(CharSequence s, int start, int count, int after) { 
        // TODO Auto-generated method stub 

       } 

       @Override 
       public void afterTextChanged(Editable s) { 
        // TODO Auto-generated method stub 
        System.out.println("AFTER TEXT CHANGE"); 
       } 
      }); 

     } 
     /* add the row values to the table layout */ 
     tableLayout.addView(tableRow); 
    } 
} 
+0

Почему вы делаете это программно? Вместо этого вы можете создать пользовательский адаптер для ListView, имеющий 1 edittext и textview для каждого элемента, и в дизайне, и в разработке будет легко и то, и другое. –

+0

спасибо за ответ, на самом деле мы создаем кроссворд-приложение, поэтому я делаю это как это. Этот шрифт кроссворда находится в gujarati character.so необходимо изменить текст на вкладках пользователей., Здесь есть своего рода транслитерация. –

+0

Это означает, что у вас есть строки * cols screen, скажем, например, 4 * 4 –

ответ

0

Я не просматриваю код в целом. Но из моего первоначального понимания вы можете сделать это любым из этих способов,

  1. Как уже упоминалось ранее, перейдите к gridview. Я не мог сделать большую часть этого вопроса из последнего комментария к вопросу, но если его проблема с прокруткой, вы могли бы попробовать макет-margin-bottom до 5 dp, чтобы он не обрезался (если это что вы имели в виду)

  2. Продолжая с помощью таблицы-макета, создайте TextWatcher() и добавьте его последовательно в цикле. Это может быть хорошо, если вы можете setId или setTag для каждого элемента, например, сначала editText получает имя, «editText1», затем «editText2» и так далее. Таким образом, в цикле вы можете получить доступ к каждому элементу на основе индекса цикла.

Смежные вопросы