按钮不起作用

时间:2011-06-29 14:39:38

标签: android android-ui

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

谢谢, 内厄姆

的Manifest.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();
}
}

3 个答案:

答案 0 :(得分: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.
    }
}

答案 1 :(得分:0)

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

答案 2 :(得分: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();
}
}
相关问题