Question

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;
}

}

Was it helpful?

Solution 2

    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");}});   

OTHER TIPS

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 findViewByIdto initialize your views. findViewById looks for a view in the current inflated layout

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;
  1. Even if you are assigning a content view, you can only use findViewById() after you have assigned the content view.

  2. If you don't set a content view, you can simply call findViewById() on the View.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top