开发者社区> 问答> 正文

安卓,fragmentTabHost中,使用自定义的view后就出错了

原本在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了,求指教。

展开
收起
爵霸 2016-03-20 11:49:58 3023 0
1 条回答
写回答
取消 提交回答
  • 这个是因为你在onCreatView()里面,view已经存在,并且有parent了,需要将parent的子view删除就可以了。 http://blog.csdn.net/renpengben/article/details/12615487

    答案来源于网络

    2019-10-14 19:14:02
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
58同城Android客户端Walle框架演进与实践之路 立即下载
Android组件化实现 立即下载
蚂蚁聚宝Android秒级编译——Freeline 立即下载