[英]Creating TextView in a View in the Navigation Drawer
I'm new to Android and have a problem with the Navigation Drawer in Android Studio. 我是Android新手,Android Studio中的导航抽屉有问题。 I want to create dynamically a TextView in one of the Navigation Drawer's view.
我想在导航抽屉的视图之一中动态创建TextView。 I cannot create a new TextView and I cannot search by id a 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;
}
Inside your onCreateView , here an example code on how you do it! 在您的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;
You don't assign any LayoutParams
to your TextView
, nor do you add it to the correct ViewGroup
. 您没有为您的
TextView
分配任何LayoutParams
,也没有将其添加到正确的ViewGroup
。 It should be added to the View
returned by onCreatView()
. 应该将其添加到
onCreatView()
返回的View
。 The following is tested and will work as an example of how to dynamically add a view: 以下内容经过测试,将作为如何动态添加视图的示例:
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.