2012-06-13 69 views
0

剛開始學習Android今天早上,需要幫助。我的應用程序中有幾個按鈕,我希望當用戶單擊某個按鈕時會顯示一個圖像,並返回按鈕以加載main.xml。使用onClick按鈕查看

代碼:

main.xml中

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="vertical" > 

    <Button 
     android:layout_marginTop="40dp" 
      android:layout_width="100dp" 
      android:layout_height="80dp" 
      android:id="@+id/b1" 
      android:text="xyz" 
      android:background="#ff3375" 
      android:layout_marginLeft="20dp" 
     /> 

    <Button 
     android:layout_marginTop="40dp" 
      android:layout_width="100dp" 
      android:layout_height="80dp" 
      android:id="@+id/b2" 
      android:layout_toRightOf="@id/b1" 
      android:text="abc" 
      android:background="#ff3375" 
      android:layout_marginLeft="80dp" 
     /></RelativeLayout> 

而且在Activity.java

package com.sam; 

import android.app.Activity; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.Button; 

public class A2Activity extends Activity { 
    /** Called when the activity is first created. */ 

    Button a,b; 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     a= (Button) findViewById(R.id.b1); 
     b= (Button) findViewById(R.id.b2); 
     a.setOnClickListener(new View.OnClickListener() { 

     public void onClick(View v) { 
      // TODO Auto-generated method stub 

     } 
    }); 
     b.setOnClickListener(new View.OnClickListener() { 

     public void onClick(View v) { 
      // TODO Auto-generated method stub 

     } 
    });}} 

現在,我需要的onclick方法打開裏面添加圖像或一個XML文件,也是一個返回按鈕返回到main.xml

+0

在你的sam.xml文件中你沒有添加任何imageview,那麼當點擊按鈕時將如何顯示圖像 – user1213202

+0

我在後臺添加了該圖像 –

回答

1

請進一步解釋你的問題。你是什​​麼意思打開一個圖像或XML文件?你的意思是創建一個位圖?你的意思是要表現出來嗎?如果是的話,在哪裏?另外,你是什麼意思,後退按鈕將返回到main.xml? main.xml是一個佈局文件,而不是一個活動。

在任何情況下,您可能意味着您希望在按下按鈕後以全屏方式打開圖像,並且當點擊設備的後退按鈕時,請返回到您創建的活動?

如果是這樣,您可以創建一個擴展Activity的新類,更新清單以便它可以訪問,並啓動它(使用startActivity)。在新的活動類中,將內容視圖設置爲顯示圖像的ImageView或具有顯示圖像的imageView的佈局文件。


開始一個新的活動,你需要調用:

startActivity(new Intent(CurrentActivity.this, NewActivity.class); 

其中「CurrentActivity」是當前的活動,你在(你的樣品中被稱爲「A2Activity」)和「NewActivity」是顯示圖像的人。

如前所述,不要忘記更新清單。

+0

雅你讓我對,我創建了一個新類,並做了所有現在在onClick方法我正在嘗試這個〜\t Intent intent = new Intent(); \t \t \t intent.setClass(view.getContext(),im1.class); \t \t \t startActivity(intent);〜,但它顯示Intent無法解析到一個類型 –

+0

現在我geting只有這個錯誤:無法從類型的靜態引用非靜態方法getContext()查看 –

+0

更新了我的答案。順便說一句,你不必聲明按鈕變量,而不是按鈕(因爲視圖也是可點擊的),而不是(因爲你以後不使用它們)。此外,java(和android)中的類應該以大寫字母開頭。這是標準。 –