在导航抽屉中的视图中创建TextView

时间:2016-07-20 16:35:40

标签: java android

我是Android新手,Android Studio中的导航抽屉有问题。我想在Navigation Drawer的一个视图中动态创建TextView。我无法创建新的TextView,我无法通过id搜索TextView

public class StatoServer extends Fragment {

View myView;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    TextView tx = new TextView(this); //doesn't work this
    tx.setText("text that change dynamically with a function");
    container.addView(tx);
    myView = inflater.inflate(statoserver, container, false);
    return myView;
}

2 个答案:

答案 0 :(得分:0)

onCreateView 中,此处提供了有关如何操作的示例代码!

View v = new View(getActivity());

v = inflater.inflate(R.layout.page2, container, false);
    View tv = v.findViewById(R.id.Ausgabe);
    ((TextView)tv).setText("TestText");
    View pl = v.findViewById(R.id.PageLayout);
    TextView Paper = new TextView(pl.getContext());
    Paper.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,     LayoutParams.WRAP_CONTENT));
    Paper.setText("Inserted TestText");
    ((LinearLayout)pl).addView(Paper);
return v;

答案 1 :(得分:0)

您不会将LayoutParams分配给TextView,也不会将其添加到正确的ViewGroup。它应添加到View返回的onCreatView()中。以下内容经过测试,可作为动态添加视图的示例:

public class OneFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.one_fragment, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {

        TextView textView = new TextView(getContext());
        textView.setLayoutParams(new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
        );
        ((ViewGroup)view).addView(textView);
        textView.setText("Some Text");
        super.onViewCreated(view, savedInstanceState);
    }
}