简体   繁体   中英

onClick Textview pass another string to intent

I made one TextView clickable. When it's clicked a new Intent is started.

articleURL  [i].setText( articleURLArr                  [i] );
articleURL[i].setPaintFlags(articleURL[i].getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
articleURL[i].setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        System.out.println ( ((TextView) v).getText().toString() );
        Intent intent = new Intent(getActivity().getBaseContext(), WebViewing.class);
        intent.putExtra("sourceURL", ((TextView) v).getText().toString());
        startActivity(intent);
    }
});

But now I wanted to pass another value to the intent. source[i] . So I tried it this way

i.putExtra("source" , ((TextView) source[v.getId()]).getText().toString());

But that gives me an ArrayIndexOutOfBoundsException with index= -1.

How can I pass another value to the intent when I handle the onclick?

In my opinion you have two options to solve this:

1- Use i inside your click listener. To do it you need to assign it to a final variable.

final int index = i;
articleURL[i].setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        System.out.println ( ((TextView) v).getText().toString() );
        Intent i = new Intent(getActivity().getBaseContext(), WebViewing.class);
        i.putExtra("sourceURL", ((TextView) v).getText().toString());
        i.putExtra("source" , ((TextView) source[index]).getText().toString());
        startActivity(i);
    }
});

2- Store the index in the view's tag (not id):

articleURL[i].setTag(i);
articleURL[i].setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        System.out.println ( ((TextView) v).getText().toString() );
        Intent i = new Intent(getActivity().getBaseContext(), WebViewing.class);
        i.putExtra("sourceURL", ((TextView) v).getText().toString());
        i.putExtra("source" , ((TextView) source[Integer.parseInt(v.getTag())]).getText().toString());
        startActivity(i);
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM