简体   繁体   中英

Can two Android Fragments use the same ids?

I want to have two or more Fragments which will be processed similarly. Can I reuse ids in each Fragment?

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" 

  <Fragment
    android:id="@+id/fragment_1"
    class="com.example.DoesSomethingToTitle"

    <TextView android:id="@+id/title" />
  </Fragment>


  <Fragment
    android:id="@+id/fragment_2"
    class="com.example.DoesSomethingToTitle"

    <TextView android:id="@id/title" />  <!-- same id -->
  </Fragment>

</FrameLayout>

And use it like this:

public class DoesSomethingToTitle {
    private String titletext;

    public DoesSomethingToTitle(String titletext) {
       this.titletext = titletext;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.feed, container, false);
        // find the title TextView and mutate it
        ((TextView) v.findViewById(R.id.title)).setText(titletext);
        return v;
    }
}

(I realize for something as simple as this, I could just specify the title string in the XML; my actual usage is more complex.)

Can I reuse ids in each Fragment?

Yes you can.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM