如何在onClick事件中使按钮变量可见?

时间:2014-01-20 21:09:57

标签: android button scope switch-statement

我希望通过使用switch语句在一个onClick事件中有两个单独的按钮但是当我这样做时,我得到了与jPBtnvFBtn变量相关的这些错误:

vfBtn cannot be resolved or is not a field

jpBtn cannot be resolved or is not a field

所以我知道这意味着点击事件无法看到按钮变量,但我想知道的问题是为什么它们不可见,因为我在onCreate中声明了它们并将它们设置为监听器?我应该在其他地方重新宣布它们吗?

这是供参考的课程:

public class MainActivity extends Activity implements android.view.View.OnClickListener {

    Button jpBtn,vfBtn;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        jpBtn = (Button)findViewById(R.id.JourneyPlanBtn);
        jpBtn.setOnClickListener(this);

        vfBtn = (Button)findViewById(R.id.FindCarBtn);
        vfBtn.setOnClickListener(this);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub


        switch(v.getId()){
        case R.id.jpBtn:
             //DO something
            Intent intent = new Intent(null, JourneyPlanner.class);
            startActivity(intent);  
        break;
        case R.id.vfBtn:
             //DO something
            Intent intent1 = new Intent(null, VechicleFinderMain.class);
            startActivity(intent);  
        break;

    }

        Intent intent = new Intent(null, JourneyPlanner.class);
        startActivity(intent);

    }

}

1 个答案:

答案 0 :(得分:1)

你需要这样做。参见案例陈述。

@Override
    public void onClick(View v) {
        // TODO Auto-generated method stub


        switch(v.getId()){
        case R.id.JourneyPlanBtn:
             //DO something
            Intent intent = new Intent(null, JourneyPlanner.class);
            startActivity(intent);  
        break;
        case R.id.FindCarBtn:
             //DO something
            Intent intent1 = new Intent(null, VechicleFinderMain.class);
            startActivity(intent);  
        break;

    }