簡體   English   中英

如何在Android Studio中將數據從適配器傳遞到片段

[英]How to pass data from adapter to fragment in android studio

字符串值,即accountname未傳遞給片段。

在適配器類中

Dashboard fragobj = new Dashboard();
bundle = new Bundle();
bundle.putString("accountname", accountName);
// set Fragment class Arguments
 fragobj.setArguments(bundle);

片段中

lvDashboard = (ListView) view.findViewById(R.id.lvDashboard);

if (getArguments()!= null) {
   accountname = getArguments().getString("accountname");
}

tasks = new ArrayList<String>();
tasks.add(tasks.size(),accountname);
lvDashboard.setAdapter(new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,tasks));

看起來不錯,但字符串值未存儲在片段的accountname變量中。

您可以在自定義適配器中使用偵聽器/回調,如下所示:

public class NameAdapter extends ArrayAdapter<String> {
  ...

  private AdapterListener mListener;

  // define listener
  public interface AdapterListener {
    void onClick(String name);
  }

  // set the listener. Must be called from the fragment
  public void setListener(AdapterListener listener) {
    this.mListener = listener;
  }

  @Override
  public View getView(final int position, View convertView, ViewGroup parent) {

    // view initialization
    ...

   // here sample for button
   btButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
              // get the name based on the position and tell the fragment via listener
              mListener.onClick(getItem(position));
            }
        });

       return convertView;
   }
}

然后在片段中設置偵聽器:

lvDashboard = (ListView) view.findViewById(R.id.lvDashboard);
lvDashboard.setAdapter(yourCustomAdapter);
yourCustomAdapter.setListener(new YourCustomAdapter.AdapterListener() {
    public void onClick(String name) {
      // do something with the string here.

    }
});

或者,您可以從ListView使用setOnItemClickListener

lvDashboard.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
      String name = parent.getItemAtPosition(position);
      // do something with the string here.
    }
 });

暫無
暫無

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

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