[android] Android findViewById() in Custom View

I've written my custom View and i want to update some other views after interacting with my custom view.

Main Layout:

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:custom="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <EditText
        android:id="@+id/display_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="text"
        android:layout_centerHorizontal="true"
        android:tag="name"
        android:ems="10" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="number"
        android:ems="10"
        android:id="@+id/id_number"
        android:layout_centerHorizontal="true"
        android:layout_below="@id/display_name"/>

    <ge.altasoft.custom_views.IdNumber
        android:id="@+id/custom_id_number"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_below="@id/id_number"
        android:paddingLeft="35dip"
        custom:firstName="@id/display_name"/>
</RelativeLayout>

Custom View Layout:

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <EditText
        android:id="@+id/id_number_custom"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="number"
        android:ems="10"
        android:paddingRight="35dip" />

    <ImageButton
        android:id="@+id/load_data_button"
        android:layout_width="30dip"
        android:layout_height="30dip"
        android:layout_centerVertical="true"
        android:src="@drawable/load_data"
        android:layout_toRightOf="@id/id_number_custom" />

</RelativeLayout>

Custom View Class, constructor and listener:

 private int firstNameViewID;

public IdNumber (Context context, AttributeSet attrs) {
        super(context, attrs);
        initViews();

        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.IdNumber);
        final int N = a.getIndexCount();
        for(int i = 0; i < N; i++){
            int attr = a.getIndex(i);
            switch(attr){
                case R.styleable.IdNumber_firstName:
                    firstNameViewID = a.getResourceId(attr, -1);
                    break;
            }
        }
        a.recycle();
    }



 private void initViews() {
        inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.id_number_edit_text_custom, this, true);
        editText = (EditText) findViewById(R.id.id_number_custom);
        loadButton = (ImageButton) findViewById(R.id.load_data_button);
        loadButton.setVisibility(RelativeLayout.INVISIBLE);
        loadData();
    }

private void loadData(){
        loadButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                EditText firstName = (EditText) findViewById(R.id.display_name);
                firstName.setText("Some Text");
            }
        });
    }

The Problem is that EditText firstName = (EditText) findViewById(R.id.display_name); returns null. I know that just calling findViewById() will search the view in the layout that i inflated it.

If it's possible, how can I get the view of EditText with id: display_name from the main layout ?

Thanks in Advance.

The answer is


If it's fixed layout you can do like that:

public void onClick(View v) {
   ViewGroup parent = (ViewGroup) IdNumber.this.getParent();
   EditText firstName = (EditText) parent.findViewById(R.id.display_name);
   firstName.setText("Some Text");
}

If you want find the EditText in flexible layout, I will help you later. Hope this help.


Change your Method as following and check it will work

private void initViews() {
    inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    inflater.inflate(R.layout.id_number_edit_text_custom, this, true);
    View view = (View) inflater.inflate(R.layout.main, null);
    editText = (EditText) view.findViewById(R.id.id_number_custom);
    loadButton = (ImageButton) view.findViewById(R.id.load_data_button);
    loadButton.setVisibility(RelativeLayout.INVISIBLE);
    loadData();
} 

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View row = convertView;
    ImageHolder holder = null;
    if (row == null) {
        LayoutInflater inflater = ((Activity) context).getLayoutInflater();
        row = inflater.inflate(layoutResourceId, parent, false);
        holder = new ImageHolder();
        editText = (EditText) row.findViewById(R.id.id_number_custom);
        loadButton = (ImageButton) row.findViewById(R.id.load_data_button);
        row.setTag(holder);
    } else {
        holder = (ImageHolder) row.getTag();
    }


    holder.editText.setText("Your Value");
    holder.loadButton.setImageBitmap("Your Bitmap Value");
    return row;
}

You can try something like this:

Inside customview constructor:

mContext = context;

Next inside customview you can call:

((MainActivity) mContext).updateText( text );

Inside MainAcivity define:

public void updateText(final String text) {

     TextView txtView = (TextView) findViewById(R.id.text);
     txtView.setText(text);
}

It works for me.


Try this in your constructor

MainActivity maniActivity = (MainActivity)context;
EditText firstName = (EditText) maniActivity.findViewById(R.id.display_name);

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to android-layout

How to check if a key exists in Json Object and get its value How to center the elements in ConstraintLayout Android - how to make a scrollable constraintlayout? Add ripple effect to my button with button background color? This view is not constrained vertically. At runtime it will jump to the left unless you add a vertical constraint Is it possible to put a ConstraintLayout inside a ScrollView? Differences between ConstraintLayout and RelativeLayout How to remove title bar from the android activity? How to have EditText with border in Android Lollipop Android: ScrollView vs NestedScrollView

Examples related to view

Empty brackets '[]' appearing when using .where SwiftUI - How do I change the background color of a View? Drop view if exists Difference between View and ViewGroup in Android How to make a view with rounded corners? How to remove all subviews of a view in Swift? How to get a view table query (code) in SQL Server 2008 Management Studio how to add button click event in android studio How to make CREATE OR REPLACE VIEW work in SQL Server? Android findViewById() in Custom View

Examples related to custom-attributes

Android findViewById() in Custom View ASP.NET MVC 4 Custom Authorize Attribute with Permission Codes (without roles) jquery: get value of custom attribute How to create a custom attribute in C# How do I read an attribute on a class at runtime?

Examples related to findviewbyid

Android findViewById() in Custom View How can I assign an ID to a view programmatically? findViewById in Fragment