在public void onClick中启动Android中的新意图

时间:2014-01-29 19:33:13

标签: android android-intent

我正在尝试开始一个新的Intent但是 new Intent(BuyTicket.this,BusPurchase.class); 以红色突出显示:“构造函数Intent(BuyTicket,Class)未定义”

我在stackoverflow中搜索过类似的问题,但没有解决这些问题。

谢谢!

package fyp.sbarcoe.tabsswipe;

public class BuyTicket extends Fragment 
{
ImageButton dubBus, luas, dart ;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
{
    View rootView = inflater.inflate(R.layout.fragment_buy, container, false);   
    dubBus = (ImageButton) rootView.findViewById(R.id.dubBus);
    luas = (ImageButton) rootView.findViewById(R.id.luas);
    dart = (ImageButton) rootView.findViewById(R.id.dart);

    dubBus.setOnClickListener(new View.OnClickListener() {public void onClick(View v)
    {
        System.out.println("Dublin Bus");
        Intent i = new Intent(BuyTicket.this, BusPurchase.class);
        startActivity(i);
    }}); 
    luas.setOnClickListener(new View.OnClickListener() {public void onClick(View v){System.out.println("Luas");}}); 
    dart.setOnClickListener(new View.OnClickListener() {public void onClick(View v){System.out.println("Dart");}});                 
    return rootView;
}

}

3 个答案:

答案 0 :(得分:2)

  

new Intent(BuyTicket.this.getActivity(), BusPurchase.class)

您需要获取片段的活动。请尝试上面的代码。

答案 1 :(得分:2)

更改

Intent i = new Intent(BuyTicket.this, BusPurchase.class);

Intent i = new Intent(getActivity(), BusPurchase.class);

Intent需要构造函数中的Activity而不是Fragment BuyTicket.this所指的

See the Intent Docs

答案 2 :(得分:0)

您的onCLickListener是一个匿名类。尝试使上下文可见:

Context mContext;

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle     savedInstanceState) 
{
View rootView = inflater.inflate(R.layout.fragment_buy, container, false);   
dubBus = (ImageButton) rootView.findViewById(R.id.dubBus);
luas = (ImageButton) rootView.findViewById(R.id.luas);
dart = (ImageButton) rootView.findViewById(R.id.dart);

mContext = getApplicationContext();

dubBus.setOnClickListener(new View.OnClickListener() {public void onClick(View v)
{
    System.out.println("Dublin Bus");
    Intent i = new Intent(mContext, BusPurchase.class);
    startActivity(i);
}}); 
luas.setOnClickListener(new View.OnClickListener() {public void onClick(View v){System.out.println("Luas");}}); 
dart.setOnClickListener(new View.OnClickListener() {public void onClick(View v){System.out.println("Dart");}});                 
return rootView;

}