[英]Android: Edit views added programmatically
所以我有一个消息应用程序,我可以在其中读取我的数据库并以编程方式呈现所有消息。 问题是,当我处于不同的布局中时,我需要扩充这些消息并随意编辑它们。 例如,
val myView = inflater.inflate(R.layout.female_messaging_fragment, container, false)
...
val convLayout = myView.findViewById<LinearLayout>(R.id.conversations_layout)
val profileLayout = LinearLayout(context)
val recentMessage = TextView(context)
recentMessage.id = 5
val recentParams = LinearLayout.LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT)
recentParams.setMargins(10, 0, 0, 0)
recentMessage.layoutParams = recentParams
recentMessage.textSize = 16f
if (didIsendLastMessage) {
val arrowIcon = ImageView(context)
Picasso.get().load(R.drawable.right_arrow).resize(50, 50).into(arrowIcon)
val imageParams = LinearLayout.LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT)
imageParams.gravity = Gravity.CENTER
arrowIcon.layoutParams = imageParams
recentMessage.setText(mostRecentMessage)
arrowAndMessageLayout.addView(arrowIcon)
arrowAndMessageLayout.addView(recentMessage)
} else {
recentMessage.setText(mostRecentMessage)
arrowAndMessageLayout.addView(recentMessage)
}
nameLastmessageLayout.addView(arrowAndMessageLayout)
// Add namne and message to profile
profileLayout.addView(nameLastmessageLayout)
convLayout.addView(profileLayout)
然后在不同的布局...
LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.female_messaging_fragment, null);
TextView text = (TextView) v.findViewById(5);
text.setText("Something");
问题是,文本始终为空,我相信这是因为我以编程方式添加了视图。 我还能在这里做什么? 谢谢!
female_messaging_fragment
将返回您的 xml 的全新布局视图对象,它可能是没有任何 TextViews 的空白布局。
要获取 TextView 对象,您需要在其中添加视图的 Layout 对象。
例如,根据您的代码,您在arrowAndMessageLayout
添加了recentMessage
,因此要获取recentMessage
的对象,您需要使用arrowAndMessageLayout
的对象,并且可以获得如下所示的内容 -
TextView text = arrowAndMessageLayout.findViewById(5);
或者
TextView text = convLayout.findViewById(5);
再次充气将返回没有你的 textview 的新容器。
希望这会帮助你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.