Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
990 views
in Technique[技术] by (71.8m points)

java - OnClickListener and Table Layout

I have an Activity with two layouts, both implemented in R.layout.main. The first one is a Relative Layout with the app's main screen, and the other is a Table Layout, holding a kind of Preferences Screen. Normally, the first one is set to visible, and the second one to gone. By clicking a button I make the Relative Layout gone, and the Table Layout visible. And here starts my problem, I wanted to set a OnClickListener to that Table Layout (which is actually an array of buttons). I tried something like:

final TableLayout table = (TableLayout)findViewById(R.id.tab);
    table.setOnClickListener(new OnClickListener(){
        public void onClick(View arg){
             Button clickedButton = (Button)arg;
             String t = (String) clickedButton.getTag();

             Toast toast = Toast.makeText(getApplicationContext(),t,Toast.LENGTH_SHORT);
             toast.show();

        }
    });

Obviously, it doesn't work. I'm quite new to Android programming, and I've been looking for a suitable solution for the whole day without any results.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It couldn't work because you are first trying to cast a TableLayout to a button... if your TableLayout is only containing buttons you could do something like:

TableLayout yourRootLayout = findView....
int count = yourRootLayout.getChildCount();
for(int i = 0; i < count; i++){
    View v = yourRootLayout.getChildAt(i);
    if(v instanceof TableRow){
        TableRow row = (TableRow)v;
        int rowCount = row.getChildCount();
        for (int r = 0; r < rowCount; r++){
            View v2 = row.getChildAt(r);
            if (v2 instanceof Button){
                Button b = (Button)v2;
                b.setOnClickListener(this);
            }
        }
    }
}

and let your activity implement OnClickListener. Just copy your Existing onClick into Activity itself...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...