为什么按钮点击时活动不会改变?

时间:2012-04-30 20:33:47

标签: android android-intent onclick android-activity android-button

当您尝试通过单击按钮来更改活动时,我发现您必须使用Intent。但是在我的代码中使用它似乎不起作用。我的代码有问题吗?

  public class SearchActivity extends Activity implements OnClickListener{

    private ListView recipes;
    Intent intent;
    Button button;
    EditText input;

    public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);

          setContentView(R.layout.searchlist);

          //EditText input = (EditText)findViewById(R.id.recipeName);
          button = (Button)findViewById(R.id.submit);
          input = (EditText)findViewById(R.id.recipeName);

          //recipes = (ListView)findViewById(R.id.recipes);
          //recipes.setAdapter(new ArrayAdapter<String> (this, R.layout.main, getResources().getStringArray(R.array.BaconSandwich)));
          button.setOnClickListener(this);
      }

      public void onClick(View clicked) {

          String value = input.getText().toString();
          Toast.makeText(this, value, Toast.LENGTH_SHORT).show();

          if(clicked == button) {
            recipes = (ListView)findViewById(R.id.recipes);
            Toast.makeText(this, "It is working for this item.", Toast.LENGTH_SHORT).show();
            Intent i = new Intent(SearchActivity.this, RecipeMethodActivity.class);
            SearchActivity.this.startActivity(i);
          }
      }

我不确定这只是一个简单的命名错误,还是我调用它的方式是错误的。任何帮助都会很棒。

此外,我已将要更改为(RecipeMethodActivity)的活动添加到Android Manifest中。

4 个答案:

答案 0 :(得分:2)

您需要在onClick方法中检查视图的ID,如下所示:

public void onClick(View clicked) {

      String value = input.getText().toString();
      Toast.makeText(this, value, Toast.LENGTH_SHORT).show();

      if(clicked.getId() == R.id.submit) {
        recipes = (ListView)findViewById(R.id.recipes);
        Toast.makeText(this, "It is working for this item.", Toast.LENGTH_SHORT).show();
        Intent i = new Intent(SearchActivity.this, RecipeMethodActivity.class);
        SearchActivity.this.startActivity(i);
      }
  }

答案 1 :(得分:1)

onClick方法中,您正在比较两个View对象的实例是否相同。显然,传递给View方法的onClick对象不是==私有实例变量Button button

您需要比较他们的ID:

if (view.getId() == R.id.button)

答案 2 :(得分:0)

我从未尝试使用clicked == button测试视图,但这应该适用于您的onCreate():

button.setOnClickListener(new OnClickListener() {
    public void onClick(View view) {
        Toast.makeText(this, "It is working for this item.", Toast.LENGTH_SHORT).show();
        Intent i = new Intent(SearchActivity.this, RecipeMethodActivity.class);
        SearchActivity.this.startActivity(i);
    }
});

答案 3 :(得分:0)

button.setOnClickListener(new View.OnClickListener() {
    public void onClick(View view) {
        Toast.makeText(this, "It is working for this item.",Toast.LENGTH_SHORT).show();
        Intent i = new Intent(view.getContext(), RecipeMethodActivity.class);
        i.putExtra("extra", extra);
        //use this ^ to transfer data from one activity to another
        startActivity(i);
        }});