原本在tabspec里的setIndicator就使用简单的字符串,没事,已经完成了。
然后想试试这里使用自定义样式,就报了个nullpointerException
下面贴下代码:
package com.example.test_fragmenttaghost;
import android.os.Bundle;
import android.view.*;
import com.example.test_fragmenttaghost.Fragment1;
import com.example.test_fragmenttaghost.Fragment2;
import com.example.test_fragmenttaghost.Fragment3;
import android.widget.*;
import android.app.Activity;
import android.view.Menu;
import android.support.v4.app.*;
import android.widget.TabHost.*;
public class MainActivity extends FragmentActivity {
private FragmentTabHost tabhost;
Class[] fragmentclass={Fragment1.class,Fragment2.class,Fragment3.class};
String[] str={"标签1","标签2","标签3"};
private LayoutInflater inflater;
int[] pictureId={R.drawable.a1,R.drawable.a2,R.drawable.a3};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inflater=LayoutInflater.from(this);
tabhost=(FragmentTabHost)super.findViewById(R.id.fragmenttabhost);
tabhost.setup(this,getSupportFragmentManager(),R.id.tabcontent);
TabSpec tabspec;
int i;
for(i=0;i<3;i++)
{
tabspec=tabhost.newTabSpec("f"+i);
tabspec.setIndicator(getItemView(i));
tabhost.addTab(tabspec,fragmentclass[i],null);
tabhost.getTabWidget().getChildAt(i);
}
}
@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;
}
public View getItemView(int index)
{
View v=inflater.inflate(R.layout.picture,null);
ImageView img=(ImageView)super.findViewById(R.id.picture1);
img.setImageResource(pictureId[index]);
TextView tv=(TextView)super.findViewById(R.id.textview);
tv.setText(str[index]);
return v;
}
}
这里比原来的代码新增加的就getItemView那段,还有layoutInflater对象的声明和实例化,还有新增加了一个用于自定义样式的xml文件(即getItemView里的R.layout.picture),最多还有原来的setIndicator(str[i])改成了现在的setIndicator(getItemView(i));
错误应该源自这几个地方,但我怎么都想不出哪里null了,求指教。