首先,我想要实现的是:每当有人点击特定按钮时(此按钮位于Listview行的每一行),根据该按钮的行应该改变颜色。
这是我迄今为止没有成功的尝试,因为它给了我错误。
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(rowResourceId, parent, false);
ImageButton add_to_cart = (ImageButton) rowView.findViewById(R.id.add_to_cart_butt);
final ListView lv = (ListView) rowView.findViewById(R.id.product_listview);
final int thePosition = position;
add_to_cart.setClickable(true);
add_to_cart.setId(position);
add_to_cart.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
lv.setFocusable(true); // This is the line where error begins
lv.setBackgroundColor(Color.GREEN);
}
});
10-06 15:56:19.302: E/AndroidRuntime(1859): FATAL EXCEPTION: main
10-06 15:56:19.302: E/AndroidRuntime(1859): java.lang.NullPointerException
10-06 15:56:19.302: E/AndroidRuntime(1859): at classes.com.example.MyExample.itemAdapter$1.onClick(itemAdapter.java:66)
10-06 15:56:19.302: E/AndroidRuntime(1859): at android.view.View.performClick(View.java:4240)
10-06 15:56:19.302: E/AndroidRuntime(1859): at android.view.View$PerformClick.run(View.java:17721)
10-06 15:56:19.302: E/AndroidRuntime(1859): at android.os.Handler.handleCallback(Handler.java:730)
10-06 15:56:19.302: E/AndroidRuntime(1859): at android.os.Handler.dispatchMessage(Handler.java:92)
10-06 15:56:19.302: E/AndroidRuntime(1859): at android.os.Looper.loop(Looper.java:137)
10-06 15:56:19.302: E/AndroidRuntime(1859): at android.app.ActivityThread.main(ActivityThread.java:5103)
10-06 15:56:19.302: E/AndroidRuntime(1859): at java.lang.reflect.Method.invokeNative(Native Method)
10-06 15:56:19.302: E/AndroidRuntime(1859): at java.lang.reflect.Method.invoke(Method.java:525)
10-06 15:56:19.302: E/AndroidRuntime(1859): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
10-06 15:56:19.302: E/AndroidRuntime(1859): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
10-06 15:56:19.302: E/AndroidRuntime(1859): at dalvik.system.NativeStart.main(Native Method)
我该如何解决?谢谢。
答案 0 :(得分:0)
只需更改rowView的颜色即可。或者编辑rowView和n的标记 创建一个if(rowView.getTag()。equals(“clicked”){// changeBack} else {// defaultBack}
答案 1 :(得分:0)
我在申请中解决问题的方法如下:
为按钮指定了onClick属性:
机器人:的onClick = “onClickChangeBackground”;
声明全局最终颜色 - defaultColor,这样如果用户错过了他想要选择的行,您可以将背景更改回原始颜色。
然后在您的主Activity(使用列表视图的那个)中开发方法如下:
public void onClickChangeBackground(View v) {
View rowView = (View) v.getParent()
ColorDrawable currentColor = (ColorDrawable) rowView.getBackground();
if(currentColor.getColor() == Color.GREEN)
rowView.setBackgroundColor(defaultColor);
else
rovView.setBackgroundColor(Color.GREEN);
}