Android - установка текста в TextView
В настоящее время я изучаю некоторый Android для школьного проекта, и я не могу найти способ динамической установки текста в TextView.
Вот мой код:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_enviar_mensaje);
err = (TextView)findViewById(R.id.texto);
err.setText("Escriba su mensaje y luego seleccione el canal.");
}
В настоящее время это не работает, и я не могу найти способ заставить его работать...
Любая помощь будет очень аппетитной... Спасибо за время, Хосе.
РЕДАКТИРОВАТЬ: Вот активность_enviar_mensaje.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
...
tools:context=".EnviarMensaje" >
...
<TextView
android:id="@+id/texto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/listaVista"
android:layout_alignParentBottom="true"
android:layout_alignRight="@+id/listaVista"
android:text="TextView" />
...
</RelativeLayout>
Под неработающим я подразумеваю, что показанный текст не изменяется в любой момент...
Ответы
Ответ 1
В вашем макете XML:
<TextView
android:id="@+id/myAwesomeTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:text="Escriba el mensaje y luego clickee el canal a ser enviado"
android:textSize="20sp" />
Затем в вашем классе активности:
// globally
TextView myAwesomeTextView = (TextView)findViewById(R.id.myAwesomeTextView);
//in your OnCreate() method
myAwesomeTextView.setText("My Awesome Text");
Ответ 2
Вставьте этот код в свой XML
<TextView
android:id="@+id/textview1"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
Вставьте этот код в свой файл JAVA
//Объявление компонентов, таких как TextView Globally, является хорошим Habbit
TextView mTextView = (TextView) findViewById(R.id.textview1);
//Поместите это в OnCreate
mTextView.setText("Welcome to Dynamic TextView");
Ответ 3
Ну, @+id/listaVista
ListView рисуется после @+id/texto
и поверх него. Поэтому измените ListView на:
android:layout_below="@+id/editText1"
в
android:layout_above="@+id/texto"
Кроме того, поскольку список рисуется после текстового просмотра, мне кажется опасным иметь android:layout_alignRight="@+id/listaVista"
в TextView. Поэтому удалите его и найдите другой способ выравнивания.
ИЗМЕНИТЬ
Взяв второй взгляд на ваш макет, я думаю, это то, что вы действительно хотите иметь:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".EnviarMensaje" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:text="Escriba el mensaje y luego clickee el canal a ser enviado"
android:textSize="20sp" />
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_alignRight="@+id/textView1"
android:layout_below="@+id/textView1"
android:ems="10"
android:inputType="text" />
<TextView
android:id="@+id/texto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/listaVista"
android:layout_alignParentBottom="true"
android:text="TextView" />
<ListView
android:id="@+id/listaVista"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/texto"
android:layout_alignParentLeft="true"
android:layout_below="@+id/editText1" >
</ListView>
</RelativeLayout>
Ответ 4
В файле макета.
<TextView
android:id="@+id/myTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Some Text"
android:textSize="18sp"
android:textColor="#000000"/>
В действии
TextView myTextView = (TextView)findViewById(R.id.myTextView);
myTextView.setText("Hello World!");
Ответ 5
В xml используйте это:
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
В операции определите представление:
Textview textView=(TextView)findViewById(R.id.textView);
textView.setText(getResources().getString(R.string.txt_hello));
В строковом файле:
<string name="txt_hello">Hello</string>
Выход: Привет
Ответ 6
Почему вы не пытаетесь назначить содержимое textview onStart(), а не onCreate()
Ответ 7
У меня была аналогичная проблема. Оказывается, у меня было два объекта TextView с тем же ID. Они были в разных файлах просмотра, и поэтому Eclipse не дал мне ошибку. Попробуйте переименовать свой идентификатор в TextView и посмотрите, не устранит ли это вашу проблему.
Ответ 8
в вашем файле activity_main.xml вставьте этот код:
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="19dp"
android:layout_marginTop="43dp"
android:text="@string/name" />
и перейдите в папку res- > values- > strings.xml
вставьте код ниже с кодом, который уже существует:
<string name="name">Escriba su mensaje y luego seleccione el canal.</string>
приведенный выше код означает, что вы создали текстовое представление с id: name (android: id = "@+ id/name" ) и назначили это текстовое представление строке с именем идентификатора (android: text = "@string/имя" )
в strings.xml, используя имя этого идентификатора для назначения текста,
Ответ 9
Попробуйте следующее:
TextView err = (TextView)findViewById(R.id.text);
Убедитесь, что вы импортируете TextView.
Ответ 10
Это должно сделать трюк:
TextView.setText("test");
Ответ 11
Пожалуйста, исправьте следующую строку:
err = (TextView)findViewById(R.id.texto);
в
err = (TextView)findViewById(R.id.err);
Ответ 12
В файле XML
<TextView
android:id="@+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="My Name"
android:textColor="#cccccc"/>
В файле активности Java
public class MainActivity1 extends Activity
{
TextView t1;
public void onCreate(Bundle onSavedInstance)
{
setContentView(R.layout.xmlfilename);
t1 = (TextView)findViewbyId(R.id.textview);
}
}
Ответ 13
сначала вы должны создать объект для текстового представления TextView show_alter
show_alert = (TextView)findViewById(R.id.show_alert);
show_alert.setText("My Awesome Text");
Ответ 14
Вы можете установить строку в textview программно, как показано ниже.
TextView textView = (TextView)findViewById(R.id.texto);
err.setText("Escriba su mensaje y luego seleccione el canal.");
или же
TextView textView = (TextView)findViewById(R.id.texto);
err.setText(getActivity().getResource().getString(R.string.seleccione_canal));
Вы можете установить строку в XML, как показано ниже.
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="19dp"
android:layout_marginTop="43dp"
android:text="Escriba su mensaje y luego seleccione el canal." />
или же
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="19dp"
android:layout_marginTop="43dp"
android:text="@string/seleccione_canal" />
Ответ 15
Как вы указали статический текст
err.setText("Escriba su mensaje y luego seleccione el canal.");
Он не изменится, он останется таким же.
Пример для динамического текста для текстового представления:
MainActivity.java
package com.example.dynamictextview;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
int count = 0;
Button clickMeBtn;
TextView dynamicText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
clickMeBtn = (Button) findViewById(R.id.button_click);
dynamicText = (TextView) findViewById(R.id.textview);
clickMeBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
count++;
dynamicText.setText("dynamic text example : " + count);
}
});
}
}
For activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.dynamictextview.MainActivity" >
<Button
android:id="@+id/button_click"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="click me"
android:layout_centerInParent="true" />
<TextView
android:id="@+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world"
android:layout_below="@id/button_click"
android:layout_centerHorizontal="true"
android:textSize="25sp"
android:layout_marginTop="20dp"
/>
</RelativeLayout>
Ответ 16
Вы должны использовать библиотеку ButterKnife
http://jakewharton.github.io/butterknife/
И используйте его как
@InjectView(R.id.texto)
TextView err;
в методе onCreate
ButterKnife.inject(this)
err.setText("Escriba su mensaje y luego seleccione el canal.");
Ответ 17
Ваш код в порядке, вы загружаете .xml, который содержит TextView
используя setContentView()
:
setContentView(R.layout.activity_enviar_mensaje);
а затем получить ссылку на TextView внутри activity_enviar_mensaje.xml
и установить текст:
err = (TextView)findViewById(R.id.texto);
err.setText("Escriba su mensaje y luego seleccione el canal.");
Проблема в том, что ваш TextView скрыт ListView
:
![enter image description here]()
Ответ 18
В вашем макете. Ваше Texto не должно содержать (android: text =...). Я бы удалил эту строку. Либо сохраните строку Java ИЛИ (android: text =...)
Ответ 19
Перейдите в свой ActivityMain и установите текст, добавив виджет из раздела виджетов и вручную изменив текст, выбрав и набрав.
Ответ 20
final TextView err = (TextView)findViewById(R.id.texto);
err.setText("Escriba su mensaje y luego seleccione el canal.");
Здесь вы можете найти все, что вам нужно о textview здесь
Ответ 21
В свой макет XML вы можете вставить
<TextView
android:id="@+id/myAwesomeTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:text="Escriba el mensaje y luego clickee el canal a ser enviado"
android:textSize="20sp"/>
Затем в вашем классе деятельности
//globally
TextView myAwesomeTextView = (TextView)findViewById(R.id.myAwesomeTextView);
//in your OnCreate() method
myAwesomeTextView.setText("My Awesome Text");
Ответ 22
Это так легко добавить динамический текст в TextView. В Android есть метод setText, с помощью которого вы можете установить динамический текст, например.
textView.setText("Hello World");
для полного объяснения вы можете посетить эту ссылку. https://www.owlbuddy.com/learn/TextView-In-Android