让我们举一个像下面这样的例子:
package xliiv.sandbox;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
public class Double_tablesActivity extends Activity {
static final String TAG = "MAIN";
LinearLayout lay;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout lay = new LinearLayout(this);
this.lay = lay;
for(int i=0; i<2; i++) {
boolean heading = (i == 0) ? true: false;
add_table(heading, "" + i);
}
this.lay.setOrientation(1);
setContentView(lay);
}
public void add_table(boolean heading, String text) {
TableLayout t = new TableLayout(this);
TableRow tr = new TableRow(this);
TextView tv = new TextView(this);
tv.setText(text);
if (heading == true) {
tv.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
TextView tv = (TextView) v;
Log.i(TAG, "onclick: " + tv.getText());
//TODO: sort 2nd table denpends on which col of first table was clicked
//??
}
});
}
tr.addView(tv);
t.addView(tr);
lay.addView(t);
}
}
我想对第二个表进行排序取决于在第一个表中单击了哪个列?假设有一个方法 table.sort(col).. 我找到了 getRootView(),所以我可以使用它并转到第二个表,但必须有更好的方法,而不是手动搜索..
更新
在 midoalageb 的回答之后,这里是上层代码的工作版本:
package xliiv.sandbox;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
public class Double_tablesActivity extends Activity {
static final String TAG = "MAIN";
LinearLayout lay;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout lay = new LinearLayout(this);
this.lay = lay;
for(int i=0; i<2; i++) {
boolean heading = (i == 0) ? true: false;
add_table(heading, "" + i);
flipper.setTag("tag" + i);
}
this.lay.setOrientation(1);
setContentView(lay);
}
public void add_table(boolean heading, String text) {
TableLayout t = new TableLayout(this);
TableRow tr = new TableRow(this);
TextView tv = new TextView(this);
tv.setText(text);
if (heading == true) {
tv.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
View root = (View) getRootView();
View view_by_tag = (View) root.findViewWithTag("tag2");
Log.i(TAG, "found table: " + flipper);
}
});
}
tr.addView(tv);
t.addView(tr);
lay.addView(t);
}
}