2016-09-28 2 views
1

Я использую специальный редактор, но проблема в том, что я не могу установить текст для моего специального редактора. Вот то, что все, что я пытался из возможных ответов на SO,Пользовательский EditText settext не устанавливает текст

setText not working for a Custom Edittext

Это не работает до сих пор. Я не получил никаких ошибок, поэтому не было известно, почему это не сработало.

Custom TextView - setText() called before constructor

Это также не работает.

XML FILE

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:id="@+id/container" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:layout_gravity="center" 
    android:background="#FFFFFF" 
    android:orientation="vertical" 
    android:paddingBottom="@dimen/activity_vertical_margin" 
    android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" > 

    <com.random.practiceproject.LinedEditText 
     android:layout_width="301dp" 
     android:inputType="text" 
     android:layout_height="match_parent" /> 


</LinearLayout> 

MainActivity

LinedEditText lt; 
    EditText et; //Normal edittext works 

    String s = "This is a sample string"; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     lt = new LinedEditText(this); 
     et = (EditText) findViewById(R.id.newt); 
     lt.setCursorVisible(true); 
     lt.setTextColor(Color.BLACK); 
     lt.setText(s,TextView.BufferType.EDITABLE); 
     et.setText(s, TextView.BufferType.EDITABLE); 
} 

Вот код,

public class LinedEditText extends EditText { 

    private static Paint linePaint; 

    static { 
     linePaint = new Paint(); 
     linePaint.setColor(Color.BLACK); 
     linePaint.setStyle(Paint.Style.STROKE); 
    } 

    public LinedEditText(Context context) 
    { 

     super(context); 

    } 

    public LinedEditText(Context context, AttributeSet attributes) { 
     super(context, attributes); 
    } 



    @Override 
    protected void onDraw(Canvas canvas) { 
     Rect bounds = new Rect(); 
     int firstLineY = getLineBounds(0, bounds); 

     /*int firstLineY=0; 

     for(int i =0;i<getLineCount();i++) 
     { 
      firstLineY = (i + 1) * getLineHeight(); 
     }*/ 

     int lineHeight = getLineHeight(); 
     int totalLines = Math.max(getLineCount(), getHeight()/lineHeight); 


     for (int i = 0; i < totalLines; i++) { 
      int lineY = firstLineY + i * lineHeight; 
      canvas.drawLine(bounds.left, lineY, bounds.right, lineY, linePaint); 
     } 

     super.onDraw(canvas); 
    } 


} 
+0

Не работает ли простой et.setText (s)? – abbath

+0

@abbath Nope тоже пробовал это. –

ответ

2

Проблема заключается в том, что вы создаете новый экземпляр LineEditText в onCreate и работаете с ним, но не добавляете в макет. В макете есть еще один экземпляр LineEditText, который вы не используете.

Таким образом, вы должны либо заменить:

с:

lt = (LinedEditText) findViewById(/*provide your id*/) 

или вам нужно добавить lt макет через ViewGroup.addView(), но я думаю, вам нужно использовать первый вариант.

+0

Просто начал вводить то же самое :) – abbath

+0

Я думал, так как я создаю экземпляр, которого будет достаточно. –

+0

@WeirdNerd no. Главное, что активность в начале жизненного цикла ничего не знает о макете. Но вы можете помочь с этим, вызвав 'setContentView'. Вы можете передать xml-макет или свою собственную ViewGroup. Затем с ней работает. В вашем случае это xml-файл с LinearLayout и унаследованный LinedEditText. Затем вам нужно взглянуть на них и работать с ними методом 'findViewById'. Но вместо этого вы создаете отдельный экземпляр 'LinedEditText' –

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