2016-12-27 123 views
0

查看關於此的所有帖子,並瞭解所有情況下人們解釋有關從適配器傳遞數據到帶有接口的片段,我使用它但我的問題是如何將數據從片段傳遞到適配器?以及如何傳遞這些數據的價值?如何在片段之間傳遞數據到適配器

這是我的適配器:

public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> { 
    private Context context; 
    List<jsonContent> jcontent; 
    private AdapterCallback callback; 
    private String etpass; 


    public DataAdapter(Context context, List<jsonContent> jcontent, AdapterCallback callback) { 

     this.context=context; 
     this.jcontent=jcontent; 
     this.callback=callback; 

    } 

    @Override 
    public DataAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) { 

     View view ; 
     if(i == R.layout.card_row) { 
      view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_row, viewGroup, false); 
     }else { 
      view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.button_card, viewGroup, false); 
     } 
     return new ViewHolder(view); 
    } 

    @Override 
    public void onBindViewHolder(final ViewHolder viewHolder, final int i) { 

     if(i == jcontent.size()) { 

      viewHolder.buttonnext.setOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View view) { 

        jcontent.removeAll(jcontent); 
        callback.MethodCallbacknext(); 

       } 
      }); 
      viewHolder.buttonprev.setOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View v) { 

        jcontent.removeAll(jcontent); 
        callback.MethodCallbackprev(); 

       } 
      }); 
      viewHolder.go.setOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View v) { 

        etpass=String.valueOf(viewHolder.editText.getText()); 
        maghalat f1 = new maghalat(); 
        Bundle args1 = new Bundle(); 
        args1.putString("sag",etpass); 
        f1.setArguments(args1); 
        callback.MethodCallbackgo(); 
       } 
      }); 

      viewHolder.cardView.setOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View v) { 

       } 
      }); 

      viewHolder.pages.setText(Integer.toString(jcontent.get(i - 1).pages)); 


     } 
     else { 
      viewHolder.title.setText(jcontent.get(i).title); 
      viewHolder.title.setTypeface(viewHolder.title.getTypeface(), Typeface.BOLD); 
      Picasso.with(context).load(jcontent.get(i).imgurl).resize(300, 400).into(viewHolder.imageView); 
     } 
    } 
    @Override 
    public int getItemCount() { 
      return jcontent.size()+1; 
    } 

    @Override 
    public int getItemViewType(int position) { 
     return (position == jcontent.size()) ? R.layout.button_card : R.layout.card_row; 
    } 


    public class ViewHolder extends RecyclerView.ViewHolder{ 

     private TextView title,pages,current; 

     private ImageView imageView; 

     private Button buttonnext,buttonprev,go; 

     private CardView cardView; 

     private EditText editText; 



     public ViewHolder(final View view) { 
      super(view); 



      title = (TextView)view.findViewById(R.id.post_title); 
      imageView=(ImageView)view.findViewById(R.id.img); 

      buttonnext =(Button)view.findViewById(R.id.next); 
      buttonprev=(Button)view.findViewById(R.id.prev); 
      go=(Button)view.findViewById(R.id.go); 

      editText=(EditText)view.findViewById(R.id.et_go_page); 

      cardView=(CardView)view.findViewById(R.id.cvv); 

      pages=(TextView)view.findViewById(R.id.number_pages); 
      current=(TextView)view.findViewById(R.id.current); 
} 
} 
} 

這是我的接口:

public interface AdapterCallback { 
    void MethodCallbackgo(); 
    void MethodCallbacknext(); 
    void MethodCallbackprev(); 
} 

,這是我的片段:

public class maghalat extends Fragment { 

    private View myFragmentView; 
    private RecyclerView recyclerView; 
    private DataAdapter adapter; 
    private String TAG = MainActivity.class.getSimpleName(); 
    private ProgressDialog pDialog; 
    List<jsonContent> listcontent=new ArrayList<>(); 

    public int dog=1; 
    public String url = "http://memaraneha.ir/category/%d9%85%d9%82%d8%a7%d9%84%d8%a7%d8%aa/page/"+String.valueOf(dog)+"/?json=get_posts"; 



    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     myFragmentView = inflater.inflate(R.layout.maghalat, container, false); 


     if(isNetworkConnected()) { 
      asyncRun(); 
     }else 
     { 
      Toast.makeText(getActivity().getApplicationContext(), "دستگاه شما به اینترنت متصل نیست!", Toast.LENGTH_LONG).show(); 
     } 
     return myFragmentView; 
    } 
    public void asyncRun(){ 
     new GetContacts().execute(); 
    } 
    public class GetContacts extends AsyncTask<Void, Void, Void> { 

     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      // Showing progress dialog 
      pDialog = new ProgressDialog(getActivity()); 
      pDialog.setMessage("Please wait..."); 
      pDialog.setCancelable(false); 
      pDialog.show(); 
     } 

     @Override 
     protected Void doInBackground(Void... arg0) { 

      HttpHandler sh = new HttpHandler(); 


      // Making a request to url and getting response 
      String jsonStr = sh.makeServiceCall(url); 


      Log.e(TAG, "Response from url: " + jsonStr); 

      if (jsonStr != null) { 
       try { 

        JSONObject jsonObj = new JSONObject(jsonStr); 


        int id=jsonObj.getInt("pages"); 


        JSONArray posts = jsonObj.getJSONArray("posts"); 
        for (int i = 0; i < posts.length(); i++) { 
         JSONObject c = posts.getJSONObject(i); 

         jsonContent jsonContent=new jsonContent(); 

         jsonContent.title=c.getString("title"); 

         //img 
         JSONObject post_img=c.getJSONObject("thumbnail_images"); 
         for (int j=0;j<post_img.length();j++) 
         { 
          JSONObject v=post_img.getJSONObject("mom-portfolio-two"); 
          jsonContent.imgurl=v.getString("url"); 
         } 
         jsonContent.pages=id; 
         listcontent.add(jsonContent); 

        } 

       } catch (final JSONException e) { 
        Log.e(TAG, "Json parsing error: " + e.getMessage()); 
        getActivity().runOnUiThread(new Runnable() { 
         @Override 
         public void run() { 
          Toast.makeText(getActivity().getApplicationContext(), 
            "Json parsing error: " + e.getMessage(), 
            Toast.LENGTH_LONG) 
            .show(); 
         } 
        }); 
       } 
      } else { 
       Log.e(TAG, "Couldn't get json from server."); 
       getActivity().runOnUiThread(new Runnable() { 
        @Override 
        public void run() { 
         Toast.makeText(getActivity().getApplicationContext(), 
           "Couldn't get json from server. Check LogCat for possible errors!", 
           Toast.LENGTH_LONG) 
           .show(); 
        } 
       }); 
      } 
      return null; 
     } 

     @Override 
     protected void onPostExecute(Void result) { 
      super.onPostExecute(result); 

      pDialog.dismiss(); 
      recyclerView=(RecyclerView)myFragmentView.findViewById(R.id.recycler_view); 
      recyclerView.setHasFixedSize(true); 
      RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity().getApplicationContext()); 
      recyclerView.setLayoutManager(layoutManager); 

      adapter=new DataAdapter(getActivity(), listcontent, new AdapterCallback() { 
       @Override 
       public void MethodCallbackgo() { 
        String gg; 
        Bundle extras = getArguments(); 
        gg = extras.getString("sag"); 
        dog= Integer.parseInt(gg); 
        url = "http://memaraneha.ir/category/%d9%85%d9%82%d8%a7%d9%84%d8%a7%d8%aa/page/"+String.valueOf(dog)+"/?json=get_posts"; 
        new GetContacts().execute(); 
       } 

       @Override 
       public void MethodCallbacknext() { 
        dog+=1; 
        url = "http://memaraneha.ir/category/%d9%85%d9%82%d8%a7%d9%84%d8%a7%d8%aa/page/"+String.valueOf(dog)+"/?json=get_posts"; 
        new GetContacts().execute(); 
       } 

       @Override 
       public void MethodCallbackprev() { 
        if (dog!=1) 
        { 
         dog-=1; 
         url = "http://memaraneha.ir/category/%d9%85%d9%82%d8%a7%d9%84%d8%a7%d8%aa/page/"+String.valueOf(dog)+"/?json=get_posts"; 
         new GetContacts().execute(); 
        }else{ 
         Toast.makeText(getActivity().getApplicationContext(),"این اولین صفحه است",Toast.LENGTH_SHORT).show(); 
        } 
       } 
      }); 

      recyclerView.setAdapter(adapter); 
     } 
    } 



    private boolean isNetworkConnected() { 
     ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE); 
     NetworkInfo ni = cm.getActiveNetworkInfo(); 
     if (ni == null) { 
      // There are no active networks. 
      return false; 
     } else 
      return true; 
    } 
    } 

想裏面go.setOnClickListener獲取編輯文本值適配器並將其傳遞給public void MethodCallbackgo() {中的片段,但沒有奏效。另一個問題是如何將狗片段內的變量值發送到適配器?

+0

不清楚爲什麼他的適配器有回調。片段應該有下一個和上一個按鈕。所有適配器需要做的就是顯示數據 –

+0

用於變量狗在片段中的更改值。和你的回答沒有回答我的問題 – erfan

+0

這是一條評論。沒有答案。鼓勵不要在評論 –

回答

1

如果理解正確,您希望將數據從回調方法調用傳遞到接口實現。

使用參數

void MethodCallbackgo(String data); 

其傳回

etpass=String.valueOf(viewHolder.editText.getText()); 
callback.MethodCallbackgo(etpass); 

另外:建議重寫的AsyncTask採取URL作爲參數。該URL並不需要是你的片段

@Override 
public void MethodCallbackgo(String data) { 
    // here you have data 
    //use it ... 
    new GetContacts().execute(url); // pass url here, for example 
} 

這什麼都不做的一個成員變量,但創建一個全新的片段,該片段從不顯示

maghalat f1 = new maghalat(); 
Bundle args1 = new Bundle(); 
args1.putString("sag",etpass); 
f1.setArguments(args1); 

就個人而言,我不不過,認爲適配器應該控制頁碼。片段(或其他類)應該包含上一個/下一個/去按鈕操作並相應地更新適配器。你已經給一個只負責在一個列表中顯示數據的類提供了「太多的責任」。

+0

中給予答案我注意你的建議和感謝。現在我不知道可以將數據從片段傳遞給適配器嗎?! 。只有這樣,我知道這個你有任何想法如何管理下一個prev去按鈕回收站的結束? – erfan

+0

您無法強制查看RecyclerView的末尾。這就是爲什麼我說它不應該是適配器的一部分,而是碎片。隨意根據你的要求創建另一個帖子,並且不要忘記接受這個用 –

+0

這個複選標記的代碼,所以你知道如何發送狗內部片段的值給適配器。問新問題,你回答? – erfan

0

聲明此在適配器

private AdapterCallback mAdaptercallback; 

適配器

public void setAdapterCallback(AdapterCallback adaptercallback){ 
    this.mAdaptercallback = adaptercallback; 
} 

創建一個方法,在你的片段做這樣

adapter.setAdapterCallback(new DataAdapter.AdapterCallback() { 


      @Override 
      public void MethodCallbackgo() { 
       String gg; 
       Bundle extras = getArguments(); 
       gg = extras.getString("sag"); 
       dog= Integer.parseInt(gg); 
       url = "http://memaraneha.ir/category/%d9%85%d9%82%d8%a7%d9%84%d8%a7%d8%aa/page/"+String.valueOf(dog)+"/?json=get_posts"; 
       new GetContacts().execute(); 
      } 

      @Override 
      public void MethodCallbacknext() { 
       dog+=1; 
       url = "http://memaraneha.ir/category/%d9%85%d9%82%d8%a7%d9%84%d8%a7%d8%aa/page/"+String.valueOf(dog)+"/?json=get_posts"; 
       new GetContacts().execute(); 
      } 

      @Override 
      public void MethodCallbackprev() { 
       if (dog!=1) 
       { 
        dog-=1; 
        url = "http://memaraneha.ir/category/%d9%85%d9%82%d8%a7%d9%84%d8%a7%d8%aa/page/"+String.valueOf(dog)+"/?json=get_posts"; 
        new GetContacts().execute(); 
       }else{ 
        Toast.makeText(getActivity().getApplicationContext(),"این اولین صفحه است",Toast.LENGTH_SHORT).show(); 
       } 
      } 
     }); 

我希望這將解決您的問題

+0

'私人AdapterCallback回調;'已經存在。它在構造函數 –

+1

中設置是的,我只是建議只有在創建適配器後才傳遞set回調。 –

+0

雖然聲明爲構造函數的一部分沒有任何問題。 –

相關問題