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



我在列表视图中有一个来自服务器数据库的动态列表。在列表的每一行中,我添加了两个图像,其中一个是可点击的,这是内置的android Star Off图像。现在,当用户单击"星空关闭"图像时,该图像应更改为"星星打开"。为此,我已经在图像上设置了 onClickListener,但我在 onClickListener 上收到错误。我也尝试过 onTouchListener,但遇到了同样的错误。这是我的完整代码如下:

类别.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);
        }
    }
}

类别.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>

日志猫

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)

我不确定这是否是原因,只有在看到日志猫时才能判断。 但请尝试ImageButton而不是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);
                    }
                }
            });

试试吧。

将 if 条件从 这:

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

对此:

if(arg0.getId() == R.id.star){
// TODO
}
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);
                }
            }
        });

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

你可以使用毕加索毕加索

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);

最新更新