簡體   English   中英

從活動到片段的數組以顯示列表

[英]Array from activity to fragment to show list

美好的一天,

如果我在主活動上聲明了一個arraylist並在列表中填充了默認值,並且希望將其顯示在自定義列表的一個片段中,那么如何訪問該片段中的列表?

謝謝

 users = new ArrayList<Users>();

在片段中

// how do I find the arraylist here?
 UserAdapter<User> adapter = new UserAdapter<User> (getContext().user);

在活動中:

Bundle bundle = new Bundle();
// Put the list in a bundle
bundle.putParcelableArrayList("users", users);
YourFragmentClass fragment = new YourFragmentClass();
fragment.setArguments(bundle);

在片段中:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // Get the list
    List<Users> users = getArguments().getParcelableArrayList("users"); 
    return inflater.inflate(R.layout.fragment, container, false);
}

首先,在您的活動中創建一個返回ArrayList的方法。

public ArrayList<User> getUsers() {
    return users;
}

然后,在您的片段中,您需要使用方法getActivity()來訪問您的活動。 從這里,您可以將調用投射到特定活動以訪問其方法。 因此,您的通話將如下所示:

ArrayList<User> users = ((MainActivity)getActivity()).getUsers();
UserAdapter<User> adapter = new UserAdapter<User>(users);

編輯:我將展示另一種方法來避免將片段與活動耦合。 在第一個示例中,您需要使用特定的Activity來獲取Users ArrayList。 這種破壞了片段的目的,即片段的可重用性。 如果將該片段放在另一個Activity中,它將無法立即工作,因為它是通過強制轉換的getActivity()調用專門綁定到MainActivity的。

更好的方法是在片段中創建一個接口,然后附加執行該接口的任何Activity。 這將允許您將片段添加到實現此接口的任何活動中,而無需更改片段的代碼。

我們的片段將如下所示:

public class ExampleFragment {

    //Create the interface that will be used to communicate with the
    //Activity. For simplicity, we'll just call it UsersProvider.
    //Whichever Activity uses this Fragment will implement this interface.
    public interface UsersProvider {
        public ArrayList<User> getUsers();
    }

    //Our UsersProvider reference. 
    private UsersProvider usersProvider;

    //Here is where we'll set the Activity as our UsersProvider.
    //We're still calling getActivity(), but we're not casting it to
    //any specific Activity, rather we're casting it as the interface.
    @Override 
    public void onAttach(Context context) {
        usersProvider = (UsersProvider) getActivity();
    }

    // onCreate, onCreateView etc... goes here
}

我們的活動將如下所示:

public class MainActivity extends Activity implements ExampleFragment.UsersProvider {

    //It's assumed that this is set somewhere else in the acitivty.
    private ArrayList<User> users;

    //onCreate, etc...

    //Implement the method from UsersProvider interface
    @Override 
    public ArrayList<User> getUsers() {
        return users;
    }
}

因此,現在以一種可以在任何活動中使用您的片段的方式進行設置,而無需更改片段中的代碼。 只需執行一個實現UsersProvider接口的活動,就可以通過調用以下代碼訪問片段中的Users ArrayList

ArrayList<User> users = usersProvider.getUsers();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM