2013-01-24 23 views
-4

可能重複:
Accessing the containing class of an inner class in Java從一個onClick監聽器調用一個方法

我知道這肯定已經回答過了,但我一直在這連續兩個晚上和我要麼不明白,要麼我搞砸了。 我想用一個按鈕調用方法。我的方法只會複製和粘貼,所以它不會打開另一個活動。

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;} 
    }; 

謝謝你看,我承認我是一個徹頭徹尾的黑客。我做到這一點的唯一原因是這個網站,第一個問題,肯定很多,但希望有人可以幫助。我不是想成爲一個吸血鬼,但我真的在這裏尋找正確的答案,如果有一個頁面,我可以閱讀,瞭解我做錯了什麼,我是所有的耳朵。

謝謝。

+3

這有**肯定* *已被回答。只需使用'PDFtester.this'而不是'this'。 –

+1

我真的不明白你想要什麼...如果你想複製/粘貼,那你爲什麼要創建一個Intent ...以及這個類是什麼:copyAsset? –

+0

爲什麼是PDFtester?老實說我有6個小時以上....... – user2002272

回答

1

使用此代碼:

@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);}   
    } 

注: - 接口,如OnClickListenerOnTouchListener等不使用this用於獲取Context嘗試使用YourActivity.thisgetApplicationContext()

+0

首先謝謝edwin。當我創建新類時,我已將它放在默認包中,因此我所有的「紅色」都將其從「默認包」移至com.example.mypackagename。你知道些什麼。再次感謝。 – user2002272

+0

在向其添加活動時要注意Manifest.xml – edwin

0
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 
相關問題