如何在android中的tab上放置监听器

时间:2012-12-14 03:25:32

标签: android android-tabactivity

这是我的标签代码。请告诉我如何通过switch语句或简单的onclick监听器将监听器放在tab1上。此吐司消息也无法正常工作

public class TabsActivity extends Activity implements OnClickListener  {

    TabHost th;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_tabs);

    th = (TabHost)findViewById(R.id.tabhost);

    th.setup();
    TabSpec specs = th.newTabSpec("tag1");
    specs.setContent(R.id.tab1);
    specs.setIndicator("Home");
    th.addTab(specs);


    specs = th.newTabSpec("tag2");
    specs.setContent(R.id.tab2);
    specs.setIndicator("Goup");
    th.addTab(specs);

    specs = th.newTabSpec("tag3");
    specs.setContent(R.id.tab3);
    specs.setIndicator("Delete");
    th.addTab(specs);

}



@Override
public void onClick(View arg0) {
    // TODO Auto-generated method stub
    switch(arg0.getId()){
    case R.id.tab1:
        Toast.makeText(TabsActivity.this, "Action Item 0 selected!", Toast.LENGTH_LONG).show();
    break;
case R.id.tab2:

    TextView text= new TextView(TabsActivity.this);
    text.setText("u have created a new tab");

    break;

case R.id.tab3:
    break;

}
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_tabs, menu);
return true;
}
}

1 个答案:

答案 0 :(得分:3)

如果您想要监听器操作,请单击选项卡,您应该使用:

th.setOnTabChangedListener(new OnTabChangeListener() {
    @Override
    public void onTabChanged(String tabId) {
        Toast.makeText(getApplicationContext(), "Click on tab: "+ tabId, Toast.LENGTH_SHORT).show();
    }
});