calling a method from an onClick listener [duplica

2019-09-22 03:52发布

问题:

Possible Duplicate:
Accessing the containing class of an inner class in Java

I know this has certainly been answered before, but I have been working on this for two straight nights and I either don't understand or I have messed something up badly. I am trying to call a method with a button. My method is only going to copy and paste so it's not opening another activity.

package com.example.copypastetest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class PDFtester extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pdftester);
            Button b1 = (Button) findViewById(R.id.button2);
            b1.setOnClickListener(new OnClickListener(){;

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            //public void work (View view){
    this is my issue??-->Intent intent = new Intent(this, copyAsset.class);
            startActivity(intent);}         
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_pdftester, menu);
        return true;}
    };

thank you for looking, I admit I am a total hack. The only reason I made it this far is this website, first question, im sure of many but hopefully someone can help. I am not trying to be a vampire but I really am looking for the correct answer here if there is a page i can read to understand what i did wrong i am all ears.

Thanks.

回答1:

Use this code:

    @Override
    public void onClick(View view) {
        // TODO Auto-generated method stub
        //public void work (View view){
        Intent intent = new Intent(PDFtester.this, copyAsset.class);
        startActivity(intent);}         
    }

Note :- Interfaces like OnClickListener,OnTouchListener etc don't use this for getting Context try to use YourActivity.this or getApplicationContext()



回答2:

b1.setOnClickListener(new OnClickListener(){;

    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub
        //public void work (View view){
this is my issue??-->Intent intent = new Intent(PDFtester.this, copyAsset.class);
        startActivity(intent);}         
    }

 // define the scope as PDFtester.this