2015-05-27 25 views
3

Buttons on another Layout and images that will be open on buttons click will be open in another layout显示不同的图像形成绘制,而无需切换活动

正如图中显示每个按钮的点击有不同的形象,我不想做出厂景,视图2,VIEW3和view4显示的图像不同的活动:

enter image description here

问:

我在Android应用程序开发的新。我想要显示不同按钮上的不同图片,而不必为每个按钮切换活动!请帮助我..在此先感谢。

+0

你肯定不希望切换活动来做到这一点。 –

回答

0

在你activity_main.xml中(或你怎么称呼它)只是把ID为布局:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:id="@+id/mainView" <!--this id--> 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" > 

然后让你的活动

Layout layout; 

再放入的onCreate场() :

layout = (Layout) findViewById (R.id.mainView); 

然后在你的onClick的按钮,你可以更改背景使用:

layout.setBackground(Drawable drawable); 

而不是“布局”,你可以使用你的布局类型。在我的情况下,它是“RelativeLayout”

编辑:根据你上次编辑,如果你想隐藏按钮上显示的图像。您可以使用片段:

http://developer.android.com/guide/components/fragments.html

,或者您可以使用

yourButton.setVisibility(View.GONE); 

藏在你onClicks按钮,然后覆盖onBackPressed方法()在您的活动,如:

@Override 
public void onBackPressed() 
{ 
    yourButton.setVisibility(View.VISIBLE);//for each button 
    super.onBackPressed(); 
} 

当然,你需要为你的按钮设置字段,并在onCreate()像上面的布局启动它们。在这两种情况下,如果按“返回”,您将再次看到按钮。

+0

谢谢Alexander Tumanin –

+0

你也可以只做一个活动显示图像,并传递给它的可绘制id在意图 – forcewill

+0

Alexandr plz tel me我的权利1)我需要添加2个布局?和一个主要的java acticity 2)代码布局,你给布局2上面? –

0

您可以使用意图,setOnClickListener为您的按钮:

@Override 
    public void onClick(View v) { 
     int id = v.getId(); 
     switch (id) { 
     case id == R.id.buttonView1: 
      Intent intent1 = new Intent(this, ShowImage.class); 
      intent.putExtra("image", R.drawable.image1); 
      startActivities(intent); 
     case id == R.id.buttonView2: 
      Intent intent2 = new Intent(this, ShowImage.class); 
      intent2.putExtra("image", R.drawable.image2); 
      startActivities(intent2); 
     } 
    } 

而且在ShowImage活动得到图片ID资源:

int image = getIntent().getIntExtra("image", R.drawable.default_image); 
ImageView imageView = (ImageView) findViewById(R.id.image_view); 
imageView.setImageResource(image); 

在ShowImage的布局:

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

    <ImageView 
     android:id="@+id/image_view" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:src="@drawable/ic_launcher" /> 

</LinearLayout>