2017-10-09 42 views
0

字符串值,即accountname未传递给片段。如何将数据从适配器传递到android studio中的片段

在适配器类别

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变量。

+2

当前代码有什么问题? –

+0

它看起来不错,但satring值没有存储在片段 –

+0

中的acountname变量中您正在使用该片段实例吗? – PedroHawk

回答

0

您可以使用监听器/回调在您的自定义适配器是这样的:

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. 

    } 
}); 

或者,你可以使用​​3210从ListView:

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. 
    } 
}); 
相关问题