java.lang.nullpointerexception即使我是textof textview

时间:2013-10-08 09:19:04

标签: android android-listview nullpointerexception textview

我有visibility=gone的一个textview,如果某些条件为真,我想将其设置为setVisibility(View.VISIBLE)

这个小部件位于list_item布局中,而list_item布局又位于listview内。

这是我的Java代码,可以将其设置为可见:

if(sex_affiche && favori_affiche){
        mSchedule = new SimpleAdapter(this.getBaseContext(),
                listItem, R.layout.affichage_item_listview, new String[] {
                        "nom", "tel","sex","favori" }, new int[] { R.id.item_nom,
                        R.id.item_tel, R.id.item_sex_jdida, R.id.item_favori });

        listedescontacts.setAdapter(mSchedule);
        registerForContextMenu(listedescontacts);

        if(sex == null){
            Log.d("null", "yes");
            TextView sex2  = (TextView)findViewById(R.id.item_sex_jdida);
            if(sex2 == null)
            Log.d("still null", "yes");
            else
                sex2.setVisibility(View.VISIBLE);
        }


        //favori.setVisibility(View.VISIBLE);

    }

我已经在oncreate中实现了它并且我重做了这个方法,但它总是为空。

1 个答案:

答案 0 :(得分:4)

您尝试访问的文本视图位于列表中;所以你不能直接访问它们。您可以做的是从适配器覆盖getView()并在其中获取视图并使其可见(盲编):

    mSchedule = new SimpleAdapter(this.getBaseContext(),
            listItem, R.layout.affichage_item_listview, new String[] {
        "nom", "tel","sex","favori" }, new int[] { R.id.item_nom,
        R.id.item_tel, R.id.item_sex_jdida, R.id.item_favori) {
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View superView = super.getView(position, convertView, parent);
            TextView sex2  = (TextView)superView.findViewById(R.id.item_sex_jdida);
            if(some_condition) {
                sex2.setVisibility(View.VISIBLE);
            } else {
                sex2.setVisibility(View.GONE);
            }
            return superView;
        }
    };