0

我正在尝试将按钮添加到我的活动中。我可以看到按钮,但按下它时没有任何反应。代码如下。

谢谢,那鸿

清单.xml:

<Button android:layout_gravity="bottom" android:layout_weight="1" android:text="Next"   android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/w_button_next"></Button>

爪哇:

private Button b3;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.wizard);
    b3 = (Button) findViewById(R.id.w_button_next);
    b3.setOnClickListener(new NextClicked());


}
class NextClicked implements Button.OnClickListener {

 public void onClick(View v) {

       Context context = v.getContext();//getApplicationContext();
       CharSequence text = "On Click";
       int duration = Toast.LENGTH_LONG;
       Toast toast = Toast.makeText(context, text, duration);
       toast.show();
    GotoNextState();
}
}
4

3 回答 3

0

这可能是您的上下文查找的问题。我总是使用对父 Activity 的引用(即你的NextClicked内部类的封闭类):

class ParentActivity extends Activity
{
    private Button b3;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.wizard);
        b3 = (Button) findViewById(R.id.w_button_next);
        b3.setOnClickListener( new View.OnClickListener() {
            public void onClick(View v) {
                Toast toast = Toast.makeText(ParentActivity.this, "On Click", Toast.LENGTH_LONG).show();
                toast.show();
                GotoNextState();
            }
        });
    }
    private void GotoNextState() {
        // Do something.
    }
}
于 2011-06-29T14:46:23.540 回答
0

我猜你可以使用 View.OnClickListener 而不是实现 Button.OnClickListener

于 2011-06-29T15:03:29.063 回答
0

如果你有很多按钮,你想听每个人,你实现第一个解决方案,如果你只有一个按钮,你可以使用Mark Allison的代码:

public class YourActivity extends Activity implements OnClickListener{
private Button b3;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.wizard);
    b3 = (Button) findViewById(R.id.w_button_next);
    b3.setOnClickListener(this);


}
 @Override
 public void onClick(View v) {

       CharSequence text = "On Click";
       int duration = Toast.LENGTH_LONG;
       Toast toast = Toast.makeText(this, text, duration);//i 've changed the context with :this
       toast.show();
    GotoNextState();
}
}
于 2011-06-29T15:06:09.647 回答