0
我對這個概念很陌生。我讀了幾個線程,但我阻止,所以先感謝您的耐心!編碼碎片和異步任務之間的通信問題
在一個片段(frag1)中,我啓動一個異步任務。我想阻止用戶在任務未完成時做任何事情,因此我想傳達完成的任務的百分比,以便用戶等待通知。
class AsyncCounter extends AsyncTask<Void, Integer, Void> {
private SetVal sender;
public AsyncCounter(SetVal sv){
this.sender = sv;
}
@Override
protected Void doInBackground(Void... params) {
for(int i=0;i<60;i++){
publishProgress(i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onProgressUpdate(Integer... values) {
Log.i("ASYNC TASK","val: "+values[0]);
sender.setVal(values[0]);
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
public interface SetVal {
public void setVal(int val);
}
public void setListener(SetVal listener) {
this.sender = listener;
}
}
我掙扎,知道如何將接口傳遞給任務:
我在一個Java SetVal.java定義的接口:
interface SetVal {
void setVal(int val);
}
我的異步任務。 我的代碼是否正確? 如何實例化異步任務?
片段:
public class Frag1 extends android.app.Fragment implements SetVal {
private static TextView txt;
private int counter;
SetVal listener;
public Frag1() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_frag1, container, false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
txt = (TextView) getActivity().findViewById(R.id.txt);
Button btn = (Button) getActivity().findViewById(R.id.btn1);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.i("Frag1", "val: " + counter);
if (counter > 0) return;
FragmentTransaction ft = getFragmentManager().beginTransaction();
Frag2 f2 = new Frag2();
ft.replace(R.id.content_frame, f2);
ft.addToBackStack("f2");
ft.commit();
}
});
Button btn2 = (Button) getActivity().findViewById(R.id.btn2);
btn2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
AsyncCounter ac = new AsyncCounter(???????);
ac.execute();
}
});
}
@Override
public void setVal(int val) {
counter = val;
}
}
MyActivity is no解決所以我嘗試與上下文,但它墜毀java.lang.ClassCastException com.narb.nestedfragments.MainActivity不能轉換爲com.narb.nestedfragments.AsyncCounter $ SetVal – narb
@narb MyActivity未解決,因爲我只是給了一個虛擬名稱。它應該是包含你的片段的活動。檢查我已經完成的更新回答 –
(包括Context和Activity),並且在嘗試執行「this.sender =(SetVal)context」時崩潰了;「與錯誤java.lang.ClassCastException:com.narb.nestedfragments.MainActivity無法轉換爲com.narb.nestedfragments.AsyncCounter $ SetVal – narb