-2

this is my first post here. I used the search function and could not find a complete answer,so I hope this is not a redundant question. I should note that I m really new to coding so maybe I did find an answer but did not realise it.

I have been asked in class to find two different ways to fill the argument in the code below.

    public class MainActivity extends AppCompatActivity implements View.OnClickListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button button = (Button)findViewById(R.id.button);
    button.setOnClickListener(this);
}

@Override
public void onClick(View v) {
    Toast.makeText(???,"Clicked!", Toast.LENGTH_LONG).show();    

the first way i suppose would be toast.makeText(MainActivity.this.getActivity(),....).show();

the second one?

  • you can use the context of the view. – njzk2 Apr 06 '17 at 17:53
  • as to how to solve such question: you are looking for a context. Look at all the objects you have in scope (here, mainly, `this` and `v`), and look at which extend context, and which have methods that return contexts. – njzk2 Apr 06 '17 at 17:54
  • `v.getContext()`..., `getApplicationContext()` etc... – rafsanahmad007 Apr 06 '17 at 17:54

2 Answers2

1

Use the MainActivity context.

   Toast.makeText(MainActivity.this,"Clicked!", Toast.LENGTH_LONG).show();    
Luiz Fernando Salvaterra
  • 4,192
  • 2
  • 24
  • 42
0

v.getContext() and this both can be used

NarenK
  • 1