我的一项活动需要一个列表视图,每行都包含自定义数字选择器。我按照这里的建议创建了数字选择器。但是,当我单击按钮时,计数器根本不会增加或减少。
以下是在我的自定义ListView
适配器中找到的代码。
public class MaterialListViewAdapter extends BaseAdapter
{
ViewHolder holder;
int counter = 0;
private ArrayList<MaterialClass> data;
public static LayoutInflater inflater = null;
public static Dialog dialog;
String materialName;
public MaterialListViewAdapter(Context applicationContext,
int materialdialogcontent, ArrayList<MaterialClass> materials)
{
this.data = materials;
inflater = (LayoutInflater)applicationContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount()
{
return data.size();
}
@Override
public Object getItem(int position)
{
return position;
}
@Override
public long getItemId(int position)
{
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
View vi = convertView;
//ViewHolder holder = new ViewHolder();
if(vi == null)
{
holder = new ViewHolder();
vi = inflater.inflate(R.layout.materialdialogcontent, null);
//Initialize Buttons and TextViews.
holder.num.setText("0");
holder.add.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
counter++;
holder.num.setText("" + counter);
}
});
holder.sub.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
counter--;
holder.sub.setText("" + counter);
}
});
//holder.pk = (NumberPicker)vi.findViewById(R.id.npMaterialAmount);
vi.setTag(holder);
}
else
{
holder = (ViewHolder)vi.getTag();
}
holder.txt.setText(data.get(position).getName());
//holder.pk.setMaxValue(20);
//holder.pk.setMinValue(0);
return vi;
}
private class ViewHolder
{
TextView txt;
Button add;
Button sub;
TextView num;
//NumberPicker pk;
}
}
当我尝试调试以查看发生了什么时,计数器甚至没有用“0”初始化。
我尝试在方法中初始化计数器getView()
,但是为了这样做,我需要将计数器设置为 final,然后出现另一个错误说
The final local variable counter cannot be assigned, since it is defined in an enclosing type.
有什么建议么?
更新了附加代码:
public class Material extends Activity
{
ArrayList<String> materialList;
ListView lv;
Button btnConfirm;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main_material);
lv = (ListView)findViewById(R.id.list);
btnConfirm = (Button)findViewById(R.id.btnConfirm);
materialList = new ArrayList<String>();
Intent i = getIntent();
materialList = i.getStringArrayListExtra("materialList");
if(materialList != null)
{
Toast t = Toast.makeText(getApplicationContext(), materialList.get(0).toString(), Toast.LENGTH_LONG);
t.show();
}
else
{
//FILL HERE LATER
}
ArrayList<MaterialClass> materials = new ArrayList<MaterialClass>();
for(String temp : materialList)
{
MaterialClass m = new MaterialClass();
m.setName(temp);
materials.add(m);
}
MaterialListViewAdapter adapter = new MaterialListViewAdapter(getApplicationContext(), R.layout.materialdialogcontent, materials);
lv.setAdapter(adapter);
}
}