简体   繁体   中英

textview clickable without xml

I'm trying to make textview clickable. I got 50 textview so I create them with java code. The problem is I don't know ho to make them clickable. If I'd work with XMl, it would be easy because the question has been asked a lot.

Here is my code:

package com.example.goo;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

public class Calendrier extends Activity implements OnClickListener{

    LinearLayout linear;
    TextView[] textViewArray = new TextView[50];
    TextView[] textViewArray2 = new TextView[50];
    LinearLayout[] layoutArray = new LinearLayout[50];
    ScrollView SV;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);        

        SV = new ScrollView(this);          
        linear = new LinearLayout(this);

        //Crée et Affiche les 50 textview sur lesquelles on cliquera
        for (int i = 0; i < 50; i++) {
            textViewArray[i] = new TextView(this);
            textViewArray[i].isClickable();
            textViewArray[i].setText("Journée" + (i+1));
            linear.addView(textViewArray[i]);
        }

        //Création de 50 textview qui seront cette fois ajoutés dans leur layout perso
        for (int i = 0; i < 50; i++) {
            textViewArray2[i] = new TextView(this);
            textViewArray2[i].setText("Journée" + (i+1));
        }

        //Création 50 layout 
        for (int i = 0; i < 50; i++) {
            layoutArray[i] = new LinearLayout(this);
        }

        for (int i = 0; i < 50; i++) {
            layoutArray[i].addView(textViewArray2[i]);
        }

        linear.setOrientation(LinearLayout.VERTICAL);

        SV.addView(linear);
        setContentView(SV);   
    }


    @Override
    public void onClick(DialogInterface dialog, int which) {
        //What should I do here ?
        //I'd like if I click on the textview n°1, the layout I create before ( layoutArray[i] = new LinearLayout(this); ) appears
        if (dialog == textViewArray[0]){
                System.out.println("this text never prints :( ");
        }

    }
}

You forget

textViewArray[i].setOnClickListener(this);

AND, you use the OnClickListener from DialogInterface. This is wrong. You must use the View.OnClickListener with a textview

First use View.OnClickListener instead of DialogInterface.OnClickListener . Then you can use

textViewArray[i].setOnClickListener(this);

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