2013-03-21 71 views
0

我有一个片段,这个布局是一个Button。如何通过onClick将视图添加到片段的LinearLayout中?

单击按钮时,将textview添加到textview_container中。

怎么样?

myfragment.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:background="#00000000" 
    android:orientation="vertical" > 
<LinearLayout 
    android:id="@+id/textview_container" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:background="#00000000" 
    android:orientation="horizontal" > 
</LinearLayout> 
<Button 
       android:id="@+id/postbutton" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:layout_gravity="right" 
       android:background="@null" 
       android:text="@string/edit" 
       android:textColor="@color/black" 
       android:textSize="14sp" /> 
</LinearLayout> 

Myfragment.java

public class AlbumListDetailFragment extends Fragment implements OnClickListener { 
    Button postButton 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     return inflater.inflate(R.layout.myfragment , container, false); 
    } 
    public void onStart() { 
     super.onStart(); 
     initViews(); 
    } 
    private void initViews() { 
      button = (Button) getView().findViewById(R.id.postbutton); 
      button.setOnClickListner{new View.onClickListener(){ 
      public void onClick(View v) { 
       //make and Textview into textview_container 
      } 
      } 
    } 
} 
+1

你必须引用容器,创建的TextView并将其追加到容器中。 – gpasci 2013-03-21 04:16:47

回答

1
LinearLayout linearLayout = (LinearLayout)findViewById(R.id.textview_container); 
TextView valueTV = new TextView(this); 
linearLayout.addView(valueTV); 
相关问题