2016-09-14 77 views
0

我想開發一些非常基本的代碼,使用startActivityForResult,我總是得到一個惱人的問題:從主要活動(只包含一個「你好單詞」editText)我打電話一個新的活動,其中只包含一個TextView,一個空的listView和一個ImageButton。當我點擊ImageButton時,它假設在我的mainActivity中意圖返回「ok」並將其打印到「hello word」editText中,但沒有任何反應。我已經閱讀了關於如何使用「StartActivity for result」的所有主題,但我沒有發現任何有用的信息。請幫助我。下面startActivityForResult Android

我的代碼是:

MainActivity

public class MainActivity extends AppCompatActivity { 

    TextView hw; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     hw = (TextView) findViewById(R.id.hw); 
     hw.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       Intent intent = new Intent(getApplicationContext(),DeviceListActivity.class); 
       int resultCode = -1; 
       startActivityForResult(intent,resultCode); 
      } 
     }); 
    } 

    @Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 

     if (requestCode == 1) { 
      if(resultCode == Activity.RESULT_OK){ 
       String result=data.getStringExtra("result"); 
       hw.setText(result); 

      } 
      if (resultCode == Activity.RESULT_CANCELED) { 
       //Write your code if there's no result 
      } 
     } 
    } 
    } 

DeviceListActivity:

public class DeviceListActivity extends Activity { 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.device_list); 

    final ImageButton nextBtn = (ImageButton) findViewById(R.id.nextBtn); 
    nextBtn.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      Intent returnIntent = new Intent(); 
      String result = "Tout va bien!"; 
      returnIntent.putExtra("result",result); 
      onActivityResult(1,1,returnIntent); 
      setResult(Activity.RESULT_OK, returnIntent); 
      finish(); 
     } 
    }); 
} 
} 
+0

嘗試http://www.javatpoint.com/android-startactivityforresult-example –

+0

remove onActivityResult(1,1,returnIntent);從DeviceListActivity –

+0

只需要2件事..從DeviceListActivity刪除** onActivityResult(1,1,returnIntent); **並將** int resultCode = -1; **與** int resultCode = 1; **在MainActivity –

回答

0
在MainActivity變化

Intent intent = new Intent(getApplicationContext(),DeviceListActivity.class); 
int resultCode = -1; 
startActivityForResult(intent,resultCode); 

Intent intent = new Intent(getApplicationContext(),DeviceListActivity.class); 
int resultCode = 1; 
startActivityForResult(intent,resultCode); 

,並在您DeviceListActivity替換爲您的代碼:

Intent returnIntent = new Intent(); 
     String result = "Tout va bien!"; 
     returnIntent.putExtra("result",result); 
     setResult(Activity.RESULT_OK, returnIntent); 
     finish(); 

希望它會幫助你。

+0

太好了,它可以工作。我現在感到非常愚蠢,現在哈哈。 我認爲這是「resultCode」的第一個值,它使一切都錯了! 非常感謝:) – badr

相關問題