[英]How to pass data from adapter to fragment in android studio
String value ie accountname
is not passed to fragment. 字符串值,即accountname
未传递给片段。
In Adapter Class 在适配器类中
Dashboard fragobj = new Dashboard();
bundle = new Bundle();
bundle.putString("accountname", accountName);
// set Fragment class Arguments
fragobj.setArguments(bundle);
In Fragment 片段中
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));
It looks fine, but string value is not stored in accountname
variable in fragment. 看起来不错,但字符串值未存储在片段的accountname
变量中。
You can use Listener/Callback in your custom Adapter something like this: 您可以在自定义适配器中使用侦听器/回调,如下所示:
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;
}
}
Then set the listener in your fragment: 然后在片段中设置侦听器:
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.
}
});
Or, you can use setOnItemClickListener from the ListView: 或者,您可以从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.