2017-06-06 63 views
-4

我正在嘗試創建一個應用程序;當我點擊一個按鈕時,它會在第二個活動中打開一個圖像。Android - 如何通過按鈕ID在新的活動中打開圖像?

例如

"button1"->"image1" , 

"button2"->"image2" 

,但我不能。有辦法做到這一點?

+0

是否要將數據從一項活動傳遞給另一項? ,就像你的情況一樣。 –

+0

檢查下面的鏈接它有一個很好的例子。
[open-an-image-in-another-activity](https://stackoverflow.com/questions/26629678/i-want-to-open-an-image-in-another-activity-when-clicked-上的項目,在最名單) –

回答

1

在您的MainActivity實施OnClickListener的按鈕:

private Button button1; 

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

    button1 = (Button) findViewById(R.id.yourItemIdInXml); 

    button1.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      // put Intent here 
     } 
    }); 
} 

中的onClick中創建一個意圖:

Intent intent = new Intent (CurrentActivity.this, ImageActivity.class); 

,並把你的圖像標識(假設你的圖片是在可繪製文件夾和具有和ID)的意圖:

intent.putExtra("IMAGE", imageId); 
startActivity(intent); 

而在接收活動onCreat E法接受這個意圖:

private ImageView image; 

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

    int imageId = getIntent().getIntExtra("IMAGE", 0); // 0 is a default value 
                 // IMAGE is a string that serves as a key, can be anything just make sure it's the same as in putExtra() 
} 

而且你可以創建後的ImageView和使用圖像標識設置:

ImageView image = (ImageView) findViewById(R.id.imageIdInXml); 
image.setImageResource(imageId); 

而對於第二個按鈕做同樣的。

這與here的基本相同,只是更詳細一點。

相關問題