首页 > 解决方案 > 如何更改膨胀视图组的子项

问题描述

我想更改膨胀视图组的子级我不知道如何访问小部件

public class MainActivity extends AppCompatActivity {
ScrollView activitymain;
LinearLayout rootLayout, subInfo;
TextView tvSerName, tvSerPrice, tvStarDate, tvNextDate;
CreateSubActivity createSubActivity;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    rootLayout = (LinearLayout) findViewById(R.id.root);
    subInfo = (LinearLayout) findViewById(R.id.subinfo);
    activitymain = (ScrollView) findViewById(R.id.activity_main);
    tvSerName = (TextView) findViewById(R.id.tvSerName);   //these are child of subinfo
    tvSerPrice = (TextView) findViewById(R.id.tvSerPrice);
    tvStarDate = (TextView) findViewById(R.id.tvStarDate);
    tvNextDate = (TextView) findViewById(R.id.tvNextDate);

}

当在另一个活动中按下按钮时,此方法有效。添加视图时,我想通过setText()更改tvSerName、tvSerPrice、tvStarDate、tvNextDate的文本,但是不起作用。我应该怎么办

void addView() {
    createSubActivity = new CreateSubActivity();

    LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    ViewGroup addview = (ViewGroup) inflater.inflate(R.layout.subinfo, null);
    tvSerName.setText("name"); // it does not works

    rootLayout.addView(addview);
}

标签: javaandroid

解决方案


您尝试在其上设置文本的视图尚未从 viewGroup 设置。

您仍然需要tvSerName = addview.findVieById(R.id.tvSerName);在设置文本之前进行设置。

void addView() {
    createSubActivity = new CreateSubActivity();

    LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    ViewGroup addview = (ViewGroup) inflater.inflate(R.layout.subinfo, null);

    //here
    tvSerName = addview.findVieById(R.id.tvSerName);

    //then set its text
    tvSerName.setText("name"); // it does not works

    rootLayout.addView(addview);
}

推荐阅读