6

I was able to make custom toast using this code

 LayoutInflater inflater = getLayoutInflater(); View layout = inflater.inflate(R.layout.custom_toast_layout, (ViewGroup)findViewById(R.id.custom_toast)); TextView text = (TextView) layout.findViewById(R.id.toast_tv); text.setText("Hello! This is a custom toast!"); Toast toast = new Toast(getApplicationContext()); toast.setDuration(Toast.LENGTH_LONG); toast.setView(layout); toast.show(); 

However, since I do not understand the purpose of LayoutInflater, I modified the code to this...

Toast toast = new Toast(getApplicationContext()); toast.setView(findViewById(R.id.custom_toast)); toast.setDuration(Toast.LENGTH_SHORT); toast.show(); 

And I get RuntimeException saying "setView must have been called"..

  • Why can't I just assign the view to toast without using LayoutInflater?

  • What is the purpose of LayoutInflater in general so that I can apply this experience to other custom views?

Edit: I am using these codes in onListItemClick() interface method.. after the content is set..

1
  • I think a good question would be "what does a LayoutInflater internally do"? Commented Nov 12, 2013 at 9:51

2 Answers 2

2

Your question have your answer, every custom view should inflate first, that's the reason you got an error with your modified code.

Sign up to request clarification or add additional context in comments.

2 Comments

if I am assigning a Button to java from xml, findViewById works fine... I do not use any inflater there.. Why use it here? Is it because The setContentView is already used once and any further content changes should be from layout inflating?
because the toast is custom & the button is not(android default). with the xml you can assign/change some property of the button.
1
LayoutInflater inflater = getLayoutInflater(); View layout = inflater.inflate(R.layout.custom_toast, (ViewGroup) findViewById(R.id.toast_layout_root)); TextView text = (TextView) layout.findViewById(R.id.text); text.setText("This is a custom toast"); Toast toast = new Toast(getApplicationContext()); toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0); toast.setDuration(Toast.LENGTH_LONG); toast.setView(layout); toast.show(); 

This is what you also did it,and it is complete right code,you have your answer, For assign custom view we have to use infalte the custom view first .

Thank you

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.