Reputation: 55
I need to activate and link a ImageButton using findViewById in this class but it won't work. I know it's something to do with not calling setContentView or extending Activity? findViewByID is underlined red and says "The method findViewById(int) is undefined for the type BuyTicket" It suggests I create it as a method.
Any help much appreciated, thanks!
package fyp.sbarcoe.tabsswipe;
public class BuyTicket extends Fragment
{
ImageButton dubBus, luas, dart ;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
dubBus = (ImageButton) findViewById(R.id.dubBus);
//dubBus.setOnClickListener(new View.OnClickListener() {public void onClick(View v){System.out.println("Dublin Bus");}});
View rootView = inflater.inflate(R.layout.fragment_buy, container, false);
return rootView;
}
}
Upvotes: 0
Views: 3519
Reputation: 133560
Change to
View rootView = inflater.inflate(R.layout.fragment_buy, container, false);
dubBus = (ImageButton) rootView.findViewById(R.id.dubBus);
Its not a Activity its a Fragment and you use the view Object for findViewById
to initialize your views. findViewById
looks for a view in the current inflated layout
Upvotes: 2
Reputation: 12919
Change your code to this:
View rootView = inflater.inflate(R.layout.fragment_buy, container, false);
dubBus = (ImageButton) rootView.findViewById(R.id.dubBus);
dubBus.setOnClickListener(new View.OnClickListener() {public void onClick(View v){System.out.println("Dublin Bus");}});
return rootView;
Even if you are assigning a content view, you can only use findViewById()
after you have assigned the content view.
If you don't set a content view, you can simply call findViewById()
on the View
.
Upvotes: 1
Reputation: 17401
View rootView = inflater.inflate(R.layout.fragment_buy, container, false);
dubBus = (ImageButton) rootView.findViewById(R.id.dubBus);
//dubBus.setOnClickListener(new View.OnClickListener() {public void onClick(View v){System.out.println("Dublin Bus");}});
Upvotes: 1