2017-04-19 144 views
1

我有一個活動,其中有一個ViewPager,在這個ViewPager中有一些片段。當屏幕上顯示數據時,我需要發送數據。所以我想在活動中實現一個將數據發送到片段的接口。通過監聽器從活動發送數據到片段

public interface SetDataToFragment { 
     void getData(List<FinanceOperationModel> aModels); 
    } 

public class FinanceMonitoringActivity extends ApiActivity2 implements FinanceMonitoringView 
     , FinanceMonitoringFragment.SaveDataInterface { 

    private SetDataToFragment mInterface; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_finance_monitoring); 
     ButterKnife.bind(this); 
     mInterface= (SetDataToFragment) this; 
... 

然後有一個錯誤:

Caused by: java.lang.ClassCastException: com.akbars.bankok.screens.financeMonitoring.FinanceMonitoringActivity cannot be cast to com.akbars.bankok.screens.financeMonitoring.SetDataToFragment

如何正確啓動界面中的活性片段使用數據?

+0

FinanceMonitoringActivity沒有實現SetDataToFragment – Pehlaj

回答

0

在您的活動中創建一個接口,並通過接口將您的數據傳遞給片段。在片段中實現該接口以獲取數據。

例如

MainActivity.class

public class MainActivity extends AppCompatActivity { 

    DataFromActivityToFragment dataFromActivityToFragment; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     FragmentA fr = new FragmentA(); 
     FragmentManager fm = getFragmentManager(); 
     dataFromActivityToFragment = (DataFromActivityToFragment) fr; 
     FragmentTransaction fragmentTransaction = fm.beginTransaction(); 
     fragmentTransaction.replace(R.id.fragment_place, fr); 
     fragmentTransaction.commit(); 


     final Handler handler = new Handler(); 

     final Runnable r = new Runnable() { 
      public void run() { 
       dataFromActivityToFragment.sendData("Hi"); 
      } 
     }; 

     handler.postDelayed(r, 5000); 


    } 

    public interface DataFromActivityToFragment { 
     void sendData(String data); 
    } 
} 

FragmentA.class

public class FragmentA extends Fragment implements MainActivity.DataFromActivityToFragment { 

    TextView text; 

    @Nullable 
    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     View rootView = inflater.inflate(R.layout.content_main, null); 
     text = (TextView) rootView.findViewById(R.id.fragment_text); 

     return rootView; 
    } 

    @Override 
    public void onViewCreated(View view, Bundle savedInstanceState) { 
     super.onViewCreated(view, savedInstanceState); 
    } 

    @Override 
    public void sendData(String data) { 
     if(data != null) 
     text.setText(data); 
    } 
} 
0

活動FinanceMonitoringActivity沒有實現SetDataToFragment,所以你不能把它轉換爲SetDataToFragment

FinanceMonitoringActivity

1

如果你想將數據發送到你可以做到這一點從viewPager適配器類或者如果你想從活動做落實活動的接口並調用該視圖尋呼機片段實現SetDataToFragment從片段中返回所需的數據。