繁体   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