0

首先我在这里尝试了示例中的提示(getActivity),但它不起作用

TextView text = (TextView)
getActivity().findViewById(R.nrOfBooksInCollection);//This results in nullpointer exception
text.setText("Text from a fragment");//This results in nullpointer exception

下面的代码也不起作用。使用以下代码在 Eclipse 中没有出现错误,它只是不会更改文本视图“nrOfBooksInCollection”中的文本。

package com.ahmad.actionBar;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TableLayout;
import android.widget.TextView;

public class FragMent2 extends Fragment
{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
    View view = inflater.inflate(R.layout.summary, null);
    SimpleBookManager testBook = new SimpleBookManager();
    TextView nrOfBooksfield = (TextView) view.findViewById(R.id.nrOfBooksInCollection);
        String text = Integer.toString(testBook.count());
        nrOfBooksfield.setText(text);//The text doesn't change at all
        nrOfBooksfield.setText("text");//Neither does this
        return inflater.inflate(R.layout.summary, container, false);
    }
    }

它在我使用活动时工作,所以 XML 文件很好。

4

1 回答 1

1

您在 ViewGroup 之外膨胀您的视图。尝试:

View view = inflater.inflate(R.layout.summary, container, null);
...
return view;
于 2012-11-15T00:13:02.327 回答