Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a reference of a view from a inflated layout

I have a huge layout for my activity that i set using setContentView(). In that layout I have a TableLayout(named tableLayout in my Activity) that I want to populate. The rows of that TableLayout are customViews in a layout file(let's call that file tablerow_layout.xml). Inside this layout i have some TextViews and ImageView. What I want to do is change the content of the TextView programatically, when I create the row. This is my code:

LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View newRow = layoutInflater.inflate(R.layout.tablerow_layout, null, false);
TextView name = (TextView) newRow. findViewById(R.id.tablerow_name);
name.setText("THIS LINE");
tableLayout.addView(newRow);

Unfortunately my app crashes when I try to change the content of the TextView. I know that I could do this using a ListView, but I usually have a small number of rows and the overhead of creating another Adapter for the ListView is preatty big.

As @ρяσѕρєя K suggested I also tried newRow.findViewById(...) instead of findViewById(...) without any difference

like image 588
Felix Avatar asked Sep 03 '15 11:09

Felix


People also ask

What does inflate View mean?

"Inflating" a view means taking the layout XML and parsing it to create the view and viewgroup objects from the elements and their attributes specified within, and then adding the hierarchy of those views and viewgroups to the parent ViewGroup.

What is layout inflation?

Layout inflation is the term used within the context of Android to indicate when an XML layout resource is parsed and converted into a hierarchy of View objects.


1 Answers

You are missing to set newRow in your Textview .

  View newRow = layoutInflater.inflate(R.layout.tablerow_layout, null, false);
  TextView name = (TextView)newRow.findViewById(R.id.tablerow_name);
like image 134
IntelliJ Amiya Avatar answered Nov 15 '22 04:11

IntelliJ Amiya