[英]I've a linear layout in a fragment. How to dynamically add a view to it from the activity?
我正在從一個片段發布數據,並通過向其添加視圖來更新另一個片段。 我沒有使用listView。 我正在使用LinearLayout。
我有一個非常簡單的懷疑。 如何通過添加另一個視圖來獲取視圖並更新它?
基本上我想膨脹已經擁有數據的linearlayout,並在添加片段的主活動中添加一個視圖。
編輯:
LinearLayout ll = (LinearLayout)fragment.getView().findViewById(R.id.commentFragmentLayout);
ViewGroup view = (ViewGroup) ll.getParent();
View customView = view;
TextView commentContext = (TextView) customView.findViewById(R.id.commentText);
commentContext.setText("hello");
view.addView(customView);
我試圖在主要活動中這樣做,但我的視圖給出了空指針異常。
編輯2:
FragmentManager fm = getSupportFragmentManager();
// You can find Fragments just like you would with a View by using FragmentManager.
android.support.v4.app.Fragment fragment = fm.findFragmentById(R.id.fragmentCommentContent);
LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(getApplicationContext().LAYOUT_INFLATER_SERVICE);
View child = inflater.inflate(R.layout.comments_list_item, null);
LinearLayout ll = (LinearLayout)fragment.getView().findViewById(R.id.commentFragmentLayout);
TextView newText = (TextView) child.findViewById(R.id.commentText);
newText.setText("Important text");
ll.addView(newText);
我試過並得到:指定的孩子已經有了父母。 首先在孩子的父母上調用removeView()。 問題是,如果我調用刪除視圖,我會丟失我在布局中插入的先前數據。
你發布的代碼沒有任何意義。 您從片段中獲取具有ID為R.id.commentFragment
的LinearLayout
的父級,在該父級中搜索TextView
以設置一些文本,然后將父級添加到自身。
我有一個非常簡單的懷疑。 如何通過添加另一個視圖來獲取視圖並更新它?
您可以使用getView()
獲取片段的View
。 您在getView()
返回的視圖上搜索所需的組件,然后將所需的視圖添加到該容器:
LinearLayout ll = (LinearLayout)fragment.getView().findViewById(R.id.commentFragmentLayout);
TextView newText = new TextView(context);
newText.setText("Important text");
ll.addView(newText);
基本上我想膨脹已經擁有數據的linearlayout,並在添加片段的主活動中添加一個視圖。
您誇大布局文件而不是已存在的視圖。 我真的不明白你想要什么,試着更好地解釋一下。
LayoutParams params =new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
lay=(LinearLayout)rootView.findViewById(R.id.Lay);
lay.addView(yourView);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.