2016-06-22 116 views
1

我有按钮,以进入(负载)这种新的片段加载视图当片段加载

buttonToFragment1.setOnClickListener(
       new OnClickListener() { 
        @Override 
        public void onClick(View arg0) { 

         // return inflater.inflate(R.layout.fragment_one, container, false); 
         Fragment fr = new FragmentOne(); 
         FragmentManager fm = getFragmentManager(); 
         FragmentTransaction fragmentTransaction = fm.beginTransaction(); 
         fragmentTransaction.replace(R.id.fragment_awal, fr); 
         fragmentTransaction.commit(); 


        } 
       } 
     ); 

当前片段(R.id.fragment_awal)现在替换加载的新片段(R.id.fragment_one),其有布局(fragment_one.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:orientation="vertical" 
    android:background="#00c4ff"> 

    <TextView 
     android:id="@+id/textView1" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:layout_weight="1" 
     android:text="Ini fragment 1" 
     android:textStyle="bold" /> 

</LinearLayout> 

和类是:

public class FragmentOne extends Fragment { 
    @Override 
    public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) { 
     //Inflate the layout for this fragment 
     return inflater.inflate(R.layout.fragment_one, container, false); 
    } 
} 

我的问题是如何加载这个TextView1,这样我可以做这样的:

TextView textFragment = (TextView)findViewById(R.id.textView1); 
textFragment.setText(" new text"); 

基本上设置文本为新加载的片段内部的视图。

编辑:我可以知道谁回答了这个问题?基本上他确实回答了这个问题,我只是有点困惑。他刚刚删除了答案。我想接受他的回答。

+0

@JuanCruzSoler,请未删除你的答案,我想接受它,你是正确的,我只是很困惑的,因为是在android开发 –

+0

新时OK完成。谢谢 –

回答

-1

您需要充气的布局之后,你可以参考TextView

@Override 
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) { 
    //Inflate the layout for this fragment 
    View view = inflater.inflate(R.layout.fragment_one, container, false); 

    TextView textFragment = (TextView) view.findViewById(R.id.textView1); 
    textFragment.setText(" new text"); 

    return view; 
} 
+0

你好,我该如何在按钮事件中调用这个'TextView'?我的意思是加载这个视图并设置文本? –

1

Fragments基本上查看包含视图的层次容器。将片段插入到视图层次结构中时,它必须有一个活动作为它的根。在任何给定时间可以存在更多的0个或更多个碎片。

用宽泛的话来说,你用另一个片段(FragmentOne)的视图替换当前视图。

要访问TextView且ID为textView1,则需要使用片段的当前视图限定findViewById方法。

更改您的片段代码:

public class FragmentOne extends Fragment { 
    @Override 
    public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) { 
     //Inflate the layout for this fragment 
     View view = inflater.inflate(R.layout.fragment_one, container, false); 

     // The findViewById method returns child views from either a Context, 
     // an Activity or another View itself. 
     TextView textFragment = (TextView) view.findViewById(R.id.textView1); 
     textFragment.setText(" new text"); 

     return view; 
    } 
}