2013-04-02 24 views
1

這可能聽起來很愚蠢,但我無法用頭包裹它。如何找出什麼意圖回調參考什麼

我有一個自定義的ListAdapter,用圖像,文本和其他所有由我的模型構成的東西填充行。現在我希望當你點擊列表中的(任何)圖像時,相機將打開並且用戶應該能夠拍照,然後被點擊的圖像應該顯示與凸輪一起拍攝的圖像。得到它?

現在,在適配器我只是做這樣的事情:

public View getView(int position, View convertView, ViewGroup parent) { 
    ...stuff... 
    ImageView image = (ImageView) elementView.findViewById(R.id.element_image); 
    image.setOnClickListener(new OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
      ((Activity) context).startActivityForResult(takePicture, 0); 
     } 
    ...other stuff... 
}); 

我添加每個ImageView的一個選項的onClick可以打開攝像頭,讓用戶拍照。 問題是上下文(我的MainActivity)在方法'onActivityResult'上得到回調,但我怎麼知道哪個回調屬於哪個ImageView?

protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) 

是否可以在意圖內發送引用? 或者它應該如何知道哪個意圖呼叫屬於哪個ImageView?

我希望你明白我的問題。否則就問。預先感謝您;)

回答

2

一個快速和簡單的解決方案,將存儲ListAdapterpositionSharedPreference。在你onActivityResult,你可以提取SharedPreference再次,要知道這是要求之一:

@Override 
public void onClick(View v) { 

    // Store in shared preferences 
    SharedPreferences sharedPref = getSharedPreferences("FileName",MODE_PRIVATE); 
    SharedPreferences.Editor prefEditor = sharedPref.edit(); 
    prefEditor.putInt("position_in_adapter",position); 
    prefEditor.commit(); 

    Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
    ((Activity) context).startActivityForResult(takePicture, 0); 
} 

,比你的活動結果:

protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent){ 

    SharedPreferences sharedPref = context.getSharedPreferences("FileName",MODE_PRIVATE); 

    // Extract again 
    int position= sharedPref.getInt("position_in_adapter", -1); 
} 

編輯:另一種選擇是使用您requestCode爲您位置。例如。

startActivityForResult(takePicture, position); 

,並在你的onActivityResult再次提取它:

protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent){ 
    // requestCode is the position in your adapter 
} 
+0

好主意,但有沒有一個簡單的解決方案?這更像是一個黑客。 – StupidBird

+0

您也可以使用requestCode來回傳遞您的位置。查看編輯。我不認爲你可以將它作爲一個參數添加到你的意圖中,因爲你無法控制攝像機應用程序返回的意圖 – Entreco

+1

@StupidBird不是黑客,這就是android的工作方式:)傳遞intent,parcelables,捆綁活動之間。 – t0mm13b