无法在onClick()事件android上将图像从一个图像更改为另一个图像

时间:2014-08-21 10:21:03

标签: android xml imageview android-arrayadapter onclicklistener

我在listview中有来自服务器数据库的动态列表。在列表的每一行中,我添加了两个图像,其中一个是可点击的,它是内置的android Star Off 图像。现在,当用户点击Star Off图像时,该图像应更改为 Star On 。为此,我在图像上设置了onClickListener,但是我在onClickListener上遇到错误。我也试过onTouchListener但是得到了同样的错误。以下是我的完整代码:

Category.java

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class Category extends Activity implements OnClickListener
{
    String url;
    String CompName,CompID;
    Strings st1=new Strings();
    TextView text;
    ImageView star;

    ListView list;
    //List<RowItem> rowItems;

    TextView txt;
    int k=0;
    int po;
    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_category);

        ActionBar action=getActionBar();
        action.setDisplayHomeAsUpEnabled(true);
        action.setIcon(R.drawable.ic_launcher);

        Intent intent=getIntent();
        CompID = intent.getStringExtra("CompID");
        url=st1.getUrl();
        connect(CompID);

        star=(ImageView)findViewById(R.id.favorite);
        star.setOnClickListener(new OnClickListener() 
        {
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                if(arg0==star)
                {
                    star.setImageResource(android.R.drawable.star_big_on);
                }
            }
        });

    }

    private void connect(String compID2) 
    {
        // TODO Auto-generated method stub
        String data;
        List<String> r = new ArrayList<String>();
        final List<String> r1=new ArrayList<String>();

        ArrayAdapter<String>adapter=new ArrayAdapter<String>(getApplicationContext(),R.layout.list_text_black,R.id.list_item,r);

        final ListView list=(ListView)findViewById(R.id.listView1);
        //CustomBaseAdapter adapter = new CustomBaseAdapter(this, rowItems);
        try 
        {
                DefaultHttpClient client = new DefaultHttpClient();

                HttpGet request = new HttpGet(url+"Retrive.php?q=comp&p="+URLEncoder.encode(compID2,"UTF-8"));
                //HttpGet request = new HttpGet("http://demo.tugain.com/tapme/retrieveVendor.php?q="+URLEncoder.encode(abc,"UTF-8"));
                HttpResponse response = client.execute(request);
                HttpEntity entity=response.getEntity();
                data=EntityUtils.toString(entity);
                Log.e("STRING", data);

                try 
                {
                   JSONArray json=new JSONArray(data);
                   for(int i=0;i<json.length(); i++)
                   {
                        JSONObject obj=json.getJSONObject(i);

                        CompName=obj.getString("fldName");//Name of the vendor.
                        CompID=obj.getString("fldVid");//ID of the vendor. 

                        Log.e("STRING", CompName);
                        Log.e("STRING",CompID);

                        r.add(CompName);
                        r1.add(CompID);
                        //star=(ImageView)findViewById(R.id.favorite+k);
                        list.setAdapter(adapter);

                        ArrayList<HashMap<String, String>>list1=new ArrayList<HashMap<String,String>>();
                        HashMap<String,String>item=new HashMap<String, String>();
                        item.put("CompName",CompName);
                        item.put("CompID",CompID);
                        list1.add(item);

                        //Toast.makeText(getApplicationContext(),list1+"",5000).show();


                        list.setOnItemClickListener(new OnItemClickListener() 
                        {
                            @Override
                            public void onItemClick(AdapterView<?> parent,View view, int position, long id) 
                            {
                            String a=Integer.toString(position);
                            po=position;
                                Log.e("selected company's id is : ",a);
                                String selected=r1.get(position);

                                //String selected=(String) list.getItemAtPosition(position);
                                Log.e("selected company's id is : ",selected);
                                Intent i1=new Intent(Category.this,Chatting.class);
                                //i1.putExtra("CompID", selected);
                                startActivity(i1);
                            }
                        });
                        String df=r1.get(po);
                        Log.e("dfsf", df);
                   }
                } 
                catch (JSONException e) 
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } catch (ClientProtocolException e) {
                Log.d("HTTPCLIENT", e.getLocalizedMessage());
            } catch (IOException e) {
                Log.d("HTTPCLIENT", e.getLocalizedMessage());
            }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.category, 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.
        switch (item.getItemId())
        {
        case android.R.id.home:
            this.finish();
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }
}

Category.xml文件

<?xml version="1.0" encoding="utf-8"?>
<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:orientation="horizontal"
    tools:ignore="UseCompoundDrawables,MangledCRLF,ContentDescription,DisableBaselineAlignment,InefficientWeight" >

    <ListView
        android:id="@+id/listView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1" >
    </ListView>

</RelativeLayout>

list_text_black.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="10dp"
    android:layout_marginTop="10dp" >

        <ImageView
            android:id="@+id/imageView3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_marginRight="50dp"
            android:adjustViewBounds="true"
            android:maxHeight="30dp"
            android:maxWidth="30dp"
            android:src="@drawable/ic_action_camera"
             />

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:layout_marginRight="10dp"
            android:adjustViewBounds="true"
            android:maxHeight="30dp"
            android:maxWidth="30dp"
            android:src="@drawable/arrow1" />

        <TextView
            android:id="@+id/list_item"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:layout_marginLeft="40dp"
            android:text="Just Test"
            android:textColor="#000000"
            android:textSize="18sp"
            android:textStyle="bold" />

        <ImageView
            android:id="@+id/favorite"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_toLeftOf="@+id/imageView1"
            android:src="@android:drawable/btn_star_big_on"
            android:clickable="true" />
    </RelativeLayout>

Logcat

08-21 15:53:41.942: D/AndroidRuntime(23553): Shutting down VM
08-21 15:53:41.942: W/dalvikvm(23553): threadid=1: thread exiting with uncaught exception (group=0x409961f8)
08-21 15:53:41.962: E/AndroidRuntime(23553): FATAL EXCEPTION: main
08-21 15:53:41.962: E/AndroidRuntime(23553): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.tutecentral.navigationdrawer/com.tutecentral.navigationdrawer.Category}: java.lang.NullPointerException
08-21 15:53:41.962: E/AndroidRuntime(23553):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1955)
08-21 15:53:41.962: E/AndroidRuntime(23553):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1980)
08-21 15:53:41.962: E/AndroidRuntime(23553):    at android.app.ActivityThread.access$600(ActivityThread.java:122)
08-21 15:53:41.962: E/AndroidRuntime(23553):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1146)
08-21 15:53:41.962: E/AndroidRuntime(23553):    at android.os.Handler.dispatchMessage(Handler.java:99)
08-21 15:53:41.962: E/AndroidRuntime(23553):    at android.os.Looper.loop(Looper.java:137)
08-21 15:53:41.962: E/AndroidRuntime(23553):    at android.app.ActivityThread.main(ActivityThread.java:4340)
08-21 15:53:41.962: E/AndroidRuntime(23553):    at java.lang.reflect.Method.invokeNative(Native Method)
08-21 15:53:41.962: E/AndroidRuntime(23553):    at java.lang.reflect.Method.invoke(Method.java:511)
08-21 15:53:41.962: E/AndroidRuntime(23553):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
08-21 15:53:41.962: E/AndroidRuntime(23553):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
08-21 15:53:41.962: E/AndroidRuntime(23553):    at dalvik.system.NativeStart.main(Native Method)
08-21 15:53:41.962: E/AndroidRuntime(23553): Caused by: java.lang.NullPointerException
08-21 15:53:41.962: E/AndroidRuntime(23553):    at com.tutecentral.navigationdrawer.Category.onCreate(Category.java:66)
08-21 15:53:41.962: E/AndroidRuntime(23553):    at android.app.Activity.performCreate(Activity.java:4465)
08-21 15:53:41.962: E/AndroidRuntime(23553):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
08-21 15:53:41.962: E/AndroidRuntime(23553):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1919)

4 个答案:

答案 0 :(得分:1)

我不确定这是否是原因,只有在看到日志猫时才会知道。但请尝试ImageButton和{/ 1> ImageView

star=(ImageButton)findViewById(R.id.favorite);
star.setTag("star");
    star.setOnClickListener(new View.OnClickListener() 
            {
                @Override
                public void onClick(View arg0) {
                    // TODO Auto-generated method stub
                    if(arg0.getTag().toString().equals("star"))
                    {
                        star.setImageResource(android.R.drawable.star_big_on);
                    }
                }
            });

尝试一下。

答案 1 :(得分:0)

更改你的if条件  这样:

if(arg0 == star){
// TODO
}

对此:

if(arg0.getId() == R.id.star){
// TODO
}

答案 2 :(得分:0)

star.setOnClickListener(new OnClickListener() 
        {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                if(arg0==star)
                {
                     star.setBackgroundColor(Color.TRANSPARENT);
                    star.setImageResource(android.R.drawable.star_big_on);
                }
            }
        });

这样我就可以显示您的图像效果

答案 3 :(得分:0)

您可以使用Picasso Picasso

import com.squareup.picasso.Picasso;

ImageView iv_user_action;
iv_user_action=(ImageView)row.findViewById(R.id.iv_user_action);

Picasso.with(context).load(R.drawable.plus).fit().placeholder(R.drawable.plus).into(iv_user_action);