2011-06-29 191 views
0

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

谢谢,那鸿

的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> 

的Java:

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(); 
} 
} 
+1

我希望具有该按钮的xml文件名为wizard.xml,而不是Manifest.xml。单击按钮时logcat中是否有任何内容? –

回答

0

这可能是您的上下文查找的问题。我总是用父活动的引用(即封闭类的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. 
    } 
} 
+0

谢谢。 ParentActivity.this不编译。除此之外,方法GotoNextState没有被调用。 – nmnir

+0

那么,在我的类中没有定义'GotoNextState()'方法,这将解释为什么它不编译,我只是用它作为如何使用'ParentActivity访问外部类的'Context'的例子。 this'。更新示例以便编译。 –

+0

谢谢马克。我的意思是,调用ParentActivity.this不编译 – nmnir

0

我想,而不是实施Button.OnClickListener可以使用View.OnClickListener

+0

谢谢。试过了,没有用。 – nmnir

+0

我认为你的按钮被按下了,但由于其他原因,它没有在烤面包中显示任何文本....我用过你的代码..它在这里工作的很好。吐司也印在这里.. –

0

如果你有一个很多按钮,你要听大家,要实现第一个解决方案,如果你只有一个按钮,就可以使用标记的代码佳佳

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(); 
} 
} 
+0

谢谢。 OnClickListener不为我编译。它应该View.OnClickListener或Button.OnClickListener。两种方式都不起作用。 – nmnir

+0

当然,View.OnClickListener是您应该使用的侦听器,如果您正在使用eclipse,请尝试在您尝试编码侦听器时使用Ctrl + Space完成代码。通常,View.OnClickListener应该适用于您 – Houcine