如何在片段中获取视图的ID

时间:2013-05-25 10:25:13

标签: android

您好我正在尝试从字符串中获取片段中某些视图的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

谢谢

3 个答案:

答案 0 :(得分:1)

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

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

然后

TextView SomeField = (TextView)V.findViewById(R.id.TxtSomeField);

答案 1 :(得分:1)

在片段内部,在findViewById:

之前添加getActivity
getActivity().findViewById(...);

答案 2 :(得分: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;
    }