簡體   English   中英

如何在此Android活動中使用findViewById()?

[英]How can I use findViewById() in this Android Activity?

我需要在此類中使用findViewById激活並鏈接ImageButton,但是它將無法正常工作。 我知道這與不調用setContentView或擴展Activity有關嗎? findViewByID用紅色下划線表示,“對於類型BuyTicket而言,方法findViewById(int)未定義”。建議我將其創建為方法。

任何幫助,不勝感激,謝謝!

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

}

改成

View rootView = inflater.inflate(R.layout.fragment_buy, container, false);
dubBus = (ImageButton) rootView.findViewById(R.id.dubBus);

它不是一個Activity,而是一個Fragment,您可以使用view Object的findViewById來初始化您的視圖。 findViewById在當前展開的布局中查找視圖

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

將代碼更改為此:

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. 即使您要分配內容視圖,也只能在分配內容視圖后使用findViewById()

  2. 如果您未設置內容視圖,則只需在View上調用findViewById()即可。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM