java - 如何更改膨胀视图组的子项
问题描述
我想更改膨胀视图组的子级我不知道如何访问小部件
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);
}
解决方案
您尝试在其上设置文本的视图尚未从 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);
}
推荐阅读
- sql-server - 带有转置的Sql Group by
- r - 在 R 中创建绘图图表以在计数和百分比之间切换
- flutter - 在 TextField 上键入时获取总数
- java - 将项目添加到 LinearLayout Android 的顶部
- assembly - SIMD 指令中间结果存储在哪里?
- sql - 如何使用 SQL,以便在一个条件下使用一个 Select,如果另一个条件则使用另一个 Select
- c - Doxygen - 隐藏详细说明
- microsoft-graph-api - Azure Graph API - 登录日志
- javascript - Slick Slider:构建比较滑块
- excel - 重复行总数