如何在android studio

时间:2017-10-09 11:01:04

标签: android android-fragments android-adapter baseadapter

字符串值,即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变量中。

1 个答案:

答案 0 :(得分:0)

您可以在自定义适配器中使用Listener / Callback,如下所示:

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.
    }
 });