hippoman
hippoman

Reputation: 330

How do you set an on click function for a dynamically created textview?

Okay so I want to dynamically create a text view, then upon clicking that textview I went it to run a function. Here is my code

 @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        super.onActivityResult(requestCode, resultCode, data);
        Bundle bundle = data.getExtras();
        contacts.add(bundle);
        String fname = bundle.getString("fname");
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        LinearLayout layout = (LinearLayout) findViewById(R.id.contactList);

        TextView textView = new TextView(this);
        textView.setLayoutParams(params);
        textView.setText(fname);
        textView.setId(idCounter);
        textView.setOnClickListener(showDetails());
        layout.addView(textView);

    }

And here is the function that I wish to call

public void showDetails(View view){
        //create intent
        //get id of textview
        //get bundle object for that textview
        //send bundle object to new activity
        //start new activity

    }

How would I get the text view to call showDetails on clicking the textview?

Upvotes: 1

Views: 41

Answers (1)

Bruno Martins
Bruno Martins

Reputation: 1436

You have to pass a View.OnClickListener instance to setOnClickListener:

View.OnClickListener listener = view -> {
    showDetails();
};
textView.setOnClickListener(listener); 

Upvotes: 2

Related Questions