长按标签

时间:2011-05-18 18:13:44

标签: android android-tabhost

有没有办法在Tabs中添加setOnLongClickListener?或者有没有其他方法可以在单击选项卡时调用一个活动,并在长时间单击同一选项卡时调用其他活动?

public class HelloTabWidget extends TabActivity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Resources res = getResources(); 
        TabHost tabHost = getTabHost(); 
        TabHost.TabSpec spec;
        Intent intent;  

        // Create an Intent to launch an Activity for the tab (to be reused)
        intent = new Intent().setClass(this, ArtistsActivity.class);

        // Initialize a TabSpec for each tab and add it to the TabHost
        spec = tabHost.newTabSpec("artists").setIndicator("Artists",
                          res.getDrawable(R.drawable.ic_tab_artists))
                      .setContent(intent);


        tabHost.addTab(spec);
        tabHost.setOnLongClickListener(new OnLongClickListener(){

            @Override
            public boolean onLongClick(View v) {
                // TODO Auto-generated method stub
////                Intent i=new Intent(getApplicationContext(),LongClickStuff.class);
//              startActivity(i);
//              return true;
                Toast.makeText(getApplicationContext(), "into long click", Toast.LENGTH_LONG).show();
                return false;
            }

        });


        // Do the same for the other tabs
        intent = new Intent().setClass(this, AlbumsActivity.class);
        spec = tabHost.newTabSpec("albums").setIndicator("Albums",
                          res.getDrawable(R.drawable.ic_tab_albums))
                      .setContent(intent);
        tabHost.addTab(spec);

        intent = new Intent().setClass(this, SongsActivity.class);
        spec = tabHost.newTabSpec("songs").setIndicator("Songs",
                          res.getDrawable(R.drawable.ic_tab_songs))
                      .setContent(intent);
        tabHost.addTab(spec);

        tabHost.setCurrentTab(2);
    }
}

1 个答案:

答案 0 :(得分:2)

测试并验证“0”是要长按的选项卡的索引:

tabHost.getTabWidget().getChildAt(0).setOnLongClickListener(new OnLongClickListener() {
    public boolean onLongClick(View v) {
        Toast.makeText(getApplicationContext(), "long click", 1).show();
        return true;
    }
});