1

I have an activity with several tabs (using the 'fixed tabs + swipe' style). Each tab layout is defined as a fragment xml file.

Eg, my activity is called ModifyCustActivity. This uses an almost-empty xml file called activity_modify_cust.xml. Each tab on this page is represented by various xml files such as fragment_modify_cust_basic and fragment_modify_cust_address etc etc. Each of these fragment xml files contains EditTexts, Spinners and more.

When the activity starts, I need to be able to access these views from the activity code, as I need to pre-populate them, and get their results once they are edited. However, because these views exist in a fragment xml file, I don't seem to be able to reach them in code. Is there a way to access a view contained in a fragment xml file?

4

2 回答 2

3

有没有办法访问片段 xml 文件中包含的视图?

是的,但是您的片段应该在 XML 布局文件中声明,这似乎是您的情况。

例如:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              ...">

    <fragment
            android:name="com.example.MyFragment"
            android:id="@+id/my_fragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

</LinearLayout>

你会像这样访问片段:

FragmentManager manager = getSupportFragmentManager();
MyFragment fragment = (MyFragment)manager.findFragmentById(R.id.my_fragment);

然后使用该fragment实例,您可以进一步访问您的视图,例如通过从更新某些特定视图的片段中调用公共方法。

更新:
假设您有一个TextView出现在片段布局中的,并且需要从活动中更新。

让它成为片段类:

public class MyFragment extends Fragment{

    private TextView textView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view =  inflater.inflate(R.layout.fragment_layout, null, false);
        textView = (TextView)view.findViewById(R.id.textView);
        return view;
    }

    public void updateTextView(String text){
        textView.setText(text);
    }
}

然后你可以TextView通过在你的活动中调用updateTextView()方法来更新:

fragment.updateTextView("text");
于 2013-08-01T12:34:55.357 回答
0

您可以从活动中访问片段视图。如果要将数据从片段发送到另一个片段。您的发送者片段必须与活动通信,并且您的活动可以操纵其他片段中的视图

http://developer.android.com/training/basics/fragments/communicating.html

于 2013-08-01T12:40:20.257 回答