原本在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了,求指教。
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。
这个是因为你在onCreatView()里面,view已经存在,并且有parent了,需要将parent的子view删除就可以了。 http://blog.csdn.net/renpengben/article/details/12615487
答案来源于网络