1

当您尝试通过单击按钮来更改活动时,我发现您必须使用 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 清单中。

4

4 回答 4

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);
      }
  }
于 2012-04-30T20:47:56.807 回答
1

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

您需要比较他们的 ID:

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

于 2012-04-30T20:50:20.693 回答
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);
    }
});
于 2012-04-30T20:47:48.697 回答
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);
        }});
于 2012-04-30T20:49:16.533 回答