虽然好像TabActivity是过时被替代了,但是刚入门android所以还是顺手学习敲了一下
遇到个问题,模拟器下的tab图标可以显示,但是放到真机里就没有图标了,drawable,dpi,9patch的知识还没搞清楚
先放上代码吧,希望有人能帮我解决
最终效果:
步骤:
1.写好三个activity作为三个tab的内容,
2.main.xml里配置TabHost,TabWidget
3.在java代码里把tab加进tabhost里面
主界面activity_main.xml
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@android:id/tabhost"
tools:context=".MainActivity" >
<!-- 注意id用内置的,不能自定义 -->
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TabWidget
android:id="@android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
</TabWidget>
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</FrameLayout>
</LinearLayout>
</TabHost>
package com.example.tab_test;
import android.app.TabActivity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TabHost;
public class MainActivity extends TabActivity {
private TabHost mytabhost;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Resources res = getResources();
mytabhost = getTabHost();
//通过TabSpec 来设定tab的Indicator Content Icon 等内容
TabHost.TabSpec tab_spec;
Intent intent;
//1
intent = new Intent(MainActivity.this,FirstActivity.class);
tab_spec = mytabhost.newTabSpec("first").setIndicator("first",res.getDrawable(R.drawable.tab_icon_sun)).setContent(intent);
mytabhost.addTab(tab_spec);
//2
intent = new Intent(MainActivity.this,SecondActivity.class);
tab_spec = mytabhost.newTabSpec("second").setIndicator("second",res.getDrawable(R.drawable.tab_icon_sun)).setContent(intent);
mytabhost.addTab(tab_spec);
//3
intent = new Intent(MainActivity.this,ThirdActivity.class);
tab_spec = mytabhost.newTabSpec("third").setIndicator("third",res.getDrawable(R.drawable.tab_icon_sun)).setContent(intent);
mytabhost.addTab(tab_spec);
mytabhost.setCurrentTab(2);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
tab按钮样式
tab_icon_sun.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_selected="true"
android:drawable="@drawable/sun_white" >
</item> <!-- 按下的时候 -->
<item
android:drawable="@drawable/sun_black" >
</item>
</selector>
关于最后 标签卡里的图标不显示的问题,参考
相当郁闷的问题,TabHost选项卡标签图标始终不出现?
http://www.cnblogs.com/lovecode/articles/2652510.html