簡體   English   中英

用於從onClickListener類顯示Toast的上下文

[英]Context to show Toast from onClickListener class

我有一個MainActivity來處理UI和按鈕,但我有一個單獨的類來處理代碼的onClickListener部分。 我的Main類定義為: public class MainActivity extends Activity ,類中的按鈕定義如下:

MyButtonListener l = new MyButtonListener();
b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(l);

MyButtonListener類定義為public class MyButtonListener extends MainActivity implements View.OnClickListener 問題來自於,當我嘗試在MyButtonListener舉杯時。 我不知道吐司的背景。 我嘗試過:MainActivity.this,MyButtonListener.this,getContextApplication()。 他們似乎都沒有工作。 這就是我試圖展示吐司的方式:

Toast.makeText(MyButtonListener.this, message, Toast.LENGTH_LONG).show();

有沒有人為了從MyButtonListener類中顯示toast而放置什么上下文?

創建全局變量

Context context;

在MainActivity和Set中

context = this;

in onCreate主要活動方法

現在像這樣在MyButtonListener構造函數中傳遞上下文

MyButtonListener l = new MyButtonListener(context);
    b1 = (Button) findViewById(R.id.button1);
    b1.setOnClickListener(l);

並在MyButtonListener中添加構造函數

private Context context;

public MyButtonListener(Context context) {
    this.context = context;
}

並在吐司中使用該上下文

將一個Context添加到MyButtonListener的構造函數中,並使用它來顯示Toast

  public MyButtonListener(Context c);

來自MainActivity

 MyButtonListener l = new MyButtonListener(this);

從參數中使用View.getContext()。

例如:

...
void onClick(View v){
    Context ctx = v.getContext();
}
...

這樣可以避免手動傳遞上下文。

它不是您獲得的上下文,而是不同引用的不同上下文,而是您可以pass the reference主活動pass the referenceMyButtonListener構造函數 ,並使用在其上傳遞的上下文。

你正在做的事實上是繼承mainactivity而不是它的創建時間,所以使用MyButtonListene.this不會在前面帶來吐司。 所以擴展主要活動是完全沒用的/沒有意義的。

我沒有看到任何理由讓MyButtonListener擴展MainActivity。

做這樣的事情:

public class MyButtonListener implements View.OnClickListener {

    private Context context;

    public MyButtonListener(Context context) {
        this.context = context;
    }

    ...

}

並從MainActivity傳遞上下文:

MyButtonListener l = new MyButtonListener(this.getApplicationContext());
MyButtonListener l = new MyButtonListener(getApplicationContext());
and create parameterize constructor  in 
MyButtonListener

and use that Context

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM