在android studio中以编程方式添加textview,但它不会显示
我想以编程方式在location.class中添加TextView,但它不显示 location.xml不包含任何TextView,因此我希望以编程方式创建TextView 我怎样才能解决这个问题在android studio中以编程方式添加textview,但它不会显示,android,textview,Android,Textview,我想以编程方式在location.class中添加TextView,但它不显示 location.xml不包含任何TextView,因此我希望以编程方式创建TextView 我怎样才能解决这个问题 public class location extends Fragment { @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(
public class location extends Fragment {
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("gateway");
RelativeLayout relativeLayout=(RelativeLayout)getActivity().findViewById(R.id.locationlayout);
Intent intent=getActivity().getIntent();
String ble_num=intent.getStringExtra("num");
int number=Integer.parseInt(ble_num);
for (int j=0; j<number; j++){
TextView textView = new TextView(getActivity());
textView.setText("123");
textView.setId(j);
relativeLayout.addView(textView);
}
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.location, container, false);
}
}
公共类位置扩展片段{
@凌驾
已创建视图上的公共void(视图,@Nullable Bundle savedInstanceState){
super.onViewCreated(视图,savedInstanceState);
getActivity().setTitle(“网关”);
RelativeLayout RelativeLayout=(RelativeLayout)getActivity().findViewById(R.id.locationlayout);
Intent Intent=getActivity().getIntent();
字符串ble_num=intent.getStringExtra(“num”);
int number=Integer.parseInt(ble_num);
对于(int j=0;j,您应该使用LinearLayout以动态方式生成它,但如果您确实想要相对性
在你的片段中:
RelativeLayout layout = (RelativeLayout)findViewById(R.id.auftrage);
final TextView textView = new TextView(this);
textView.setText("Text ");
int curTextViewId = 2;//or some id number
textView.setId(curTextViewId);
final RelativeLayout.LayoutParams params =
new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.BELOW, prevTextViewId);
textView.setLayoutParams(params);
layout.addView(textView, params);
谢谢。我最终使用linearlayout生成它。我发现它比使用relativelayout更容易。