2015-05-07 4 views
-1

Привет всем и извините, если на этот вопрос будет дан ответ.Change ImageView с кнопкой

Я занимаюсь географической игрой, и я хочу знать, как изменить свой ImageView в зависимости от кнопки, которую я нажимаю.

Например, у меня есть карта Европы со стрелкой, указывающей на Испанию. Я хочу, чтобы при нажатии кнопки «Испания» карта превращается в карту со стрелкой, указывающей на Португалию.

Я пробовал этот код, но я не могу заставить его работать:

public void cargar_por(View v){ 
    ImageView iv = (ImageView)findViewById(R.id.imageView); 
    if(flag==false){ 
     Drawable por=setFeatureDrawable(iv,por); 
     iv.setImageDrawable(R.drawable.por); 
     flag = true; 
    } 
    else{ 
     flag=false; 
    } 
} 

Как я могу это сделать?

Заранее спасибо.

EDIT: Я собираюсь добавить полный код.

файл XML выглядит следующим образом:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" 
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" 
android:paddingRight="@dimen/activity_horizontal_margin" 
android:paddingTop="@dimen/activity_vertical_margin" 
android:paddingBottom="@dimen/activity_vertical_margin" 
tools:context=".MainActivity"> 

<LinearLayout 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:layout_alignParentTop="true" 
    android:layout_centerHorizontal="true" 
    android:weightSum="1"> 

    <LinearLayout 
     android:orientation="vertical" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_gravity="center_horizontal" 
     android:layout_weight="0.91" 
     android:weightSum="1" 
     android:focusableInTouchMode="true" 
     android:focusable="true"> 

     <LinearLayout 
      android:orientation="vertical" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:layout_gravity="center_horizontal"> 

      <Chronometer 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:id="@+id/chronometer" 
       android:layout_gravity="right" 
       android:enabled="true" /> 

      <TextView 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:textAppearance="?android:attr/textAppearanceLarge" 
       android:text="Nivel 1" 
       android:id="@+id/textView5" 
       android:layout_gravity="center_horizontal" 
       android:background="#ffffffff" /> 
     </LinearLayout> 

     <TableLayout 
      android:layout_width="fill_parent" 
      android:layout_height="fill_parent"> 

      <ImageView 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:id="@+id/map" 
       android:src="@drawable/spa" 
       android:visibility="visible" 
       android:layout_weight="0.93" /> 

     </TableLayout> 

    </LinearLayout> 

    <LinearLayout 
     android:orientation="horizontal" 
     android:layout_width="match_parent" 
     android:layout_height="131dp" 
     android:layout_gravity="center_horizontal" 
     android:background="#3f073dff"> 

     <LinearLayout 
      android:orientation="vertical" 
      android:layout_width="fill_parent" 
      android:layout_height="fill_parent" 
      android:id="@+id/layout1"> 

      <LinearLayout 
       android:orientation="horizontal" 
       android:layout_width="fill_parent" 
       android:layout_height="60dp" 
       android:weightSum="1"> 

       <LinearLayout 
        android:orientation="horizontal" 
        android:layout_width="wrap_content" 
        android:layout_height="match_parent" 
        android:weightSum="1"> 

        <Button 
         android:layout_width="181dp" 
         android:layout_height="match_parent" 
         android:text="ESPAÑA" 
         android:id="@+id/button5" 
         android:onClick="cargar_por" /> 
       </LinearLayout> 

       <LinearLayout 
        android:orientation="horizontal" 
        android:layout_width="match_parent" 
        android:layout_height="match_parent"> 

        <Button 
         android:layout_width="match_parent" 
         android:layout_height="match_parent" 
         android:text="PORTUGAL" 
         android:id="@+id/button6" /> 
       </LinearLayout> 
      </LinearLayout> 

      <LinearLayout 
       android:orientation="horizontal" 
       android:layout_width="match_parent" 
       android:layout_height="match_parent" 
       android:layout_gravity="center_horizontal" 
       android:weightSum="1"> 

       <LinearLayout 
        android:orientation="horizontal" 
        android:layout_width="wrap_content" 
        android:layout_height="match_parent" 
        android:layout_weight="0.40" 
        android:weightSum="1"> 

        <Button 
         android:layout_width="match_parent" 
         android:layout_height="58dp" 
         android:text="FRANCIA" 
         android:id="@+id/button7" 
         android:layout_weight="0.86" /> 
       </LinearLayout> 

       <LinearLayout 
        android:orientation="horizontal" 
        android:layout_width="wrap_content" 
        android:layout_height="match_parent" 
        android:layout_weight="0.40"> 

        <Button 
         android:layout_width="match_parent" 
         android:layout_height="59dp" 
         android:text="ITALIA" 
         android:id="@+id/button8" /> 
       </LinearLayout> 

      </LinearLayout> 
     </LinearLayout> 
    </LinearLayout> 
</LinearLayout> 

И код Java, как это:

package marti.victor.geografia; 

import android.graphics.drawable.Drawable; 
import android.os.SystemClock; 
import android.support.v7.app.ActionBarActivity; 
import android.os.Bundle; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.*; 
import android.widget.Button; 
import android.widget.Chronometer; 
import android.widget.ImageButton; 
import android.widget.ImageView; 


public class Juego extends ActionBarActivity { 
// boolean flag = false; 
    ImageView image = (ImageView) findViewById(R.id.map); 
    Button but; 
    int a = 0; 
    Chronometer myChronometer; 


@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.juego); 
    myChronometer = (Chronometer)findViewById(R.id.chronometer); 
    myChronometer.start(); 



} 


@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.menu_main_activity2, menu); 
    return true; 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    // Handle action bar item clicks here. The action bar will 
    // automatically handle clicks on the Home/Up button, so long 
    // as you specify a parent activity in AndroidManifest.xml. 
    int id = item.getItemId(); 

    //noinspection SimplifiableIfStatement 
    if (id == R.id.action_settings) { 
     return true; 
    } 

    return super.onOptionsItemSelected(item); 
} 



/*public void cargar_por(View v){ 
    ImageView iv = (ImageView)findViewById(R.id.imageView); 
    but=(Button)findViewById(R.id.button5); 
    but.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 

      iv.setImageDrawable(R.drawable.por); 
     } 
    }); 
}*/ 
} 
+0

напишите свой полный код. У меня есть некоторые сомнения и проверьте, полезно ли это –

+2

. Вы не поставили setOnClickListener, поэтому ваша картинка не меняется. –

ответ

1

попробовать этот

ImageView iv = (ImageView)findViewById(R.id.imageView); 
    spainbutton.setOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View v) { 

        iv.setImageDrawable(R.drawable.por);  
       } 
      }); 
в вашем случае

я думаю флаг работает неправильно ,

+0

Извините, но Android Studio говорит, что Iv должен быть объявлен окончательным. В противном случае он не будет строить ... :( –

+0

@ VíctorMartíCalleja поэтому объявите его окончательным или поставьте его как внешнее поле –

+0

@ VíctorMartíCalleja объявите его чуть ниже объявления вашего класса. –

Смежные вопросы