2017-10-09 84 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. 
    } 
}); 
相關問題