[英]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.