1

嗨,我正在尝试从字符串中获取片段中某些视图的 id,但是它似乎不起作用......片段是否有特殊情况?

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View singleplayerView = inflater.inflate(R.layout.singleplayer_tab, container, false);
        setupMap();
        return singleplayerView;
    }

    private void setupRank() {
        TextView view = (TextView) getByStringId("rank0");
        view.setText("hello");
    }



    private final View getByStringId(final String id) {
        return findViewById(getResources().getIdentifier(id, "id", getActivi

ty().getPackageName()));
        }

所以我试图在用于我的片段的布局中设置 textView 字段 rank0 ......但现在它得到一个 NUllPointer 因为它找不到 id

谢谢

4

3 回答 3

1

您可以在片段中的 onCreateView() 中定义布局,如下所示:

View V = new View(getActivity());
V = inflater.inflate(R.layout.fragment_layout,container, false);

然后

TextView SomeField = (TextView)V.findViewById(R.id.TxtSomeField);
于 2013-05-25T10:31:46.163 回答
1

在片段内部,在 findViewById 之前添加 getActivity:

getActivity().findViewById(...);
于 2013-05-25T10:33:06.537 回答
1

尝试这个,

String id;
@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle extra = getArguments();
            id = extra.getString("id", "");
}


@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_calendar_details, container, false);
        Button b = (Button) view.findViewById(id);
        return view;
    }
于 2013-05-25T10:34:11.620 回答