今天遇到一需求,tabhost点击某个标签头,标签页不切换,直接进入另一activity;其他标签头正常
如下图点击“本地”标签头直接跳到另一个activity:
开始想通过OnTabChangeListener来实现,没有成功,后来通过设置标签头view的OnTouchListener里的onTouch()事件里来实现,返回true;
代码如下:
import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
import android.widget.Toast;
import com.bobo.splayer.R;
public class MainActivity extends TabActivity {
private TabHost mTabHost;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_vr_main);
mTabHost=getTabHost();//(TabHost) findViewById(android.R.id.tabhost);
mTabHost.addTab(getSpec("tab1","精选",new Intent(this,Activity1.class))) ;
mTabHost.addTab(getSpec("tab2","影视",new Intent(this,Activity2.class))) ;
mTabHost.addTab(getSpec("tab3","游戏",new Intent(this,Activity3.class))) ;
mTabHost.addTab(getSpec("tab4","设置",new Intent(this,Tab4.class))) ;
mTabHost.addTab(getLocalSpec("tab5","本地",R.id.tv_local)) ;
mTabHost.setOnTabChangedListener(new OnTabChangeListener() {
@Override
public void onTabChanged(String tabId) {
/* if(tabId.equals("tab5")){
Intent i=new Intent(getApplicationContext(), TargetActivity.class);
startActivity(i);
}*/
System.out.println("TabChanged---tabId="+tabId);
}
});
}
private TabSpec getLocalSpec(String tag, String desc, int viewID) {
TabSpec tabSpec = mTabHost.newTabSpec(tag);
TextView view=(TextView) View.inflate(this, R.layout.act_vr_main_tabwiget, null);
view.setText(desc);
view.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction()==MotionEvent.ACTION_DOWN){
Toast.makeText(getApplicationContext(), "touch,touch", 0).show();
System.out.println("touch,touch");
Intent i=new Intent(getApplicationContext(), TargetActivity.class);
startActivity(i);
}
return true;
}
});
tabSpec.setIndicator(view);
tabSpec.setContent(viewID);
return tabSpec;
}
private TabSpec getSpec(String tag, String desc, Intent intent) {
TabSpec tabSpec = mTabHost.newTabSpec(tag);
//tabSpec.setIndicator(desc);
TextView view=(TextView) View.inflate(this, R.layout.act_vr_main_tabwiget, null);
view.setText(desc);
tabSpec.setIndicator(view);
tabSpec.setContent(intent);
return tabSpec;
}
}