我在Mainactivity.java中写了一个openDialog()用来做事件响应.但在按钮OnClick属性中加入openDialog()没效果,提示openDialog()找不到public class MainActivity extends Activity {
private TextView txtView;
    @Override
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        this.txtView = (TextView) findViewById(R.id.textView1);        if(this.txtView!=null){            this.txtView.setText("Hello World");
        }
    }
    public void openDialog(){  
        AlertDialog.Builder builder = new AlertDialog.Builder(this);  
        builder.setTitle("Hello");  
        builder.setMessage("Hello World \n");  
        builder.setNegativeButton("OK",null);  
        builder.show();  
    }     @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
}
添加Button的On Click属性eclipseadtjava

解决方案 »

  1.   

        可视化设计界面只是提供属性设置,触发事件用代码实现就可以了:
    public class MainActivity extends Activity {
        private TextView txtView;
        @Override
        protected void onCreate(Bundle savedInstanceState) {     
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            this.txtView = (TextView) findViewById(R.id.textView1);
     
            if(this.txtView!=null){
     
                this.txtView.setText("Hello World");
            } Button button = (Button) findViewById(R.id.button_id);
            button.setOnClickListener(new View.OnClickListener() {
                 public void onClick(View v) {
                     openDialog();
                 }
             });
        }
        public void openDialog(){  
            AlertDialog.Builder builder = new AlertDialog.Builder(this);  
            builder.setTitle("Hello");  
            builder.setMessage("Hello World \n");  
            builder.setNegativeButton("OK",null);  
            builder.show();  
        } 
     
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.main, menu);
            return true;
        }
         
    }
      

  2.   

    想在xml里定义onClick的方法的话,一定要用这种格式:
     public void openDialog(View view) {
         // ...
     }
    方法要定义成public,并且接受一个View做参数,你这里少了这个参数是不行的。
    或者用2楼的方法,用代码实现。