I think I figured out my problem. I need to do this work in the PlaceholderFragment where onCreateView is defined. When I call findviewbyid here it dosen't return null.
Android, set text for an EditText on startup
-
19-07-2023 - |
문제
So I have a simple android app where I take text from a text file (that part is working) and I want to set that text to EditText.setText(). The problem I'm having is that I cannot do this in the onCreate() method because the EditText field and the UI hasn't been created yet(from what it seems).
My question is where would be a good place to do this? Is there a function that is called right after the GUI elements are created?
public class MainActivity extends ActionBarActivity
{
private final String FILE_NAME = "awayReply";
private EditText myEditMessage;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null)
{
getSupportFragmentManager().beginTransaction().add(R.id.container, new PlaceholderFragment()).commit();
}
}
@Override
protected void onStart()
{
String message = readMessage();
myEditMessage = (EditText)findViewById(R.id.edit_message);
if(myEditMessage != null)
{
myEditMessage.setText(message, TextView.BufferType.EDITABLE);
}
}
XML Layout:
<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"
android:orientation="horizontal"
android:paddingBottom="16dp"
android:paddingTop="16dp" >
<EditText
android:id="@+id/edit_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="@string/lbl_message"
android:inputType="textImeMultiLine" />
<Button
android:id="@+id/btn_update"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/edit_message"
android:onClick="updateMessage"
android:text="@string/lbl_update" />
<ToggleButton
android:id="@+id/toggle_away"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/lbl_enable"
android:layout_alignBottom="@+id/lbl_enable"
android:layout_toRightOf="@+id/edit_message"
android:textOff="Disabled"
android:textOn="Enabled"
android:onClick="toggleEnabled" />
</RelativeLayout>
해결책 2
다른 팁
You can't set your text in a TextView until you inflate your layout with
setContentView(R.layout.main_activity);
in the Activity's OnCreate
Once that happens you can do:
EditText editText = (EditText)findViewById(R.id.myEditText)
Full Example:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); // this needs to happen first
EditText editText = (EditText)findViewById(R.id.myEditText)
editText.setText("my text", TextView.BufferType.EDITABLE); // <-- needs that second parameter
}
Edit: updated for EditText instead of TextView