Lobstw Lobstw - 7 months ago 26
Java Question

Accessing custom view with findViewById

I have a custom

EditText
set up in its own file
CustomEditText.java
:

public class CustomEditText extends EditText {
...
}


I reference it in my activity's XML with the full name:

<LinearLayout>

<com.example.app.CustomEditText
...
/>
</LinearLayout>


I use my custom EditText by putting this in my activity class:

LayoutInflater inflater = getLayoutInflater();
LinearLayout linearLayout= (LinearLayout) inflater.inflate(R.layout.activity_main, null);

CustomEditText customEditText = new CustomEditText(this, null);

linearLayout.addView(customEditText);
this.setContentView(linearLayout);


I can access this
customEditText
normally:

customEditText.setText("Hello!")


But I can't access this
customEditText
later on with
findViewById(R.id.customEditText)
as this returns an empty
EditText
.

Is there something that I'm missing?

Answer

If you add the view in XML, you don't need to add it programmatically with

CustomEditText customEditText = new CustomEditText(this, null);
linearLayout.addView(customEditText);

Set android:id="@+id/customEditText on your CustomEditText in xml and you will be able to find the view using findViewById(R.id.customEditText)