How to findViewById form another XML file?

11,501

Solution 1

From insinde your MyAdapter class you can override the getView method (that's the one that produces the item renderers on demand).

After recycling / inflating the proper layout for the current item (say convertView), you can access all of its children using the findViewById method called on the convertView:

    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        // initialize, inflate convertView from your layout if needed; 
        tvDisplayDate = (EditText)convertView.findViewById(R.id.editd);
        // populate convertView with the item's details
    }

Solution 2

Try this View view = LayoutInflater.from(getApplication()).inflate(R.layout.item, null);

How you can see, static from() method takes 1 argument(Context) and you obtains LayoutInflater from given Context, in your case it will be your Activity where you want to inflate View.

Hope it helps!

Share:
11,501
SWE
Author by

SWE

Updated on June 04, 2022

Comments

  • SWE
    SWE almost 2 years

    I connent an addevent.java with addevent.xml is content a listview, the listview take its element from another XML file "item.xml"

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >
    
            <Button
                android:id="@+id/d"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_alignParentTop="true"
                android:drawablePadding="0dip"
                android:drawableRight="@drawable/icon_name" />
    
            <EditText
                android:id="@+id/en"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentTop="true"
                android:layout_toLeftOf="@+id/d" >
            </EditText>
    
    </LinearLayout>
    

    now I need to findviewbyId not from basic xml file but form another "item.xml"

    I tried LayoutInflater as this, code but it isn't work:

    public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.addevent);
            myList = (ListView) findViewById(R.id.MyList);
            myList.setItemsCanFocus(true);
            myAdapter = new MyAdapter();
            myList.setAdapter(myAdapter);
    
    
            final LayoutInflater factory = getLayoutInflater();
    
            final View textEntryView = factory.inflate(R.layout.item, null);
    
            tvDisplayDate = (EditText)textEntryView.findViewById(R.id.editd);
            btnChangeDate=(Button)textEntryView.findViewById(R.id.d);
    

    any help please