我完全陷入了一些东西。我试图在Android环境中简单地解除对被点击的对象的引用,但是对于我来说生活中找不到方法。Android从OnClick获取绑定对象
我有一个MainView,我加载json对象,我将这些对象传递给我的适配器,我找到这些列表。我已经点击列表中的TextView项来捕获点击事件。
问题:OnClick触发了,但是我无法从那里找回原始的绑定对象,或者我不知道该怎么做?我试图使用一个位置变量,当getView函数被调用每行时增加,但是当OnClick发生时我的位置总是指向列表中的最后一条记录。我也尝试在MainView中实现onItemClick,但似乎从未开火。
我该如何取回绑定到我的TextView的对象?提前感谢您的帮助。
public class MainActivity extends AppCompatActivity {
private static final String LOCATION_KEY = "location";
SharedPreferences pref;
SharedPreferences.Editor editor;
public JSONObject jsonObj = null;
ListView mainList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(com.digitour.www.R.layout.activity_main);
// Load state from shared preferences
pref= getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
editor=pref.edit();`enter code here`
mainList = (ListView) findViewById(com.digitour.www.R.id.checkableList);
try {
jsonObj=new JSONObject(pref.getString("json",null));
// Bind Data and pass the json object read from a file to the adapter
MainViewAdapter customListViewAdapter = new MainViewAdapter(this, jsonObj);
mainList.setAdapter(customListViewAdapter);
} catch (Exception e) {
e.printStackTrace();
}
}
}
下面是适配器代码:
public class MainViewAdapter extends BaseAdapter {
private LayoutInflater layoutInflater;
private Context context;
private JSONArray listItems;
private int positionPrivate;
private JSONObject jsonObj;
public MainViewAdapter(Context context, JSONObject jsonObj) {
layoutInflater = LayoutInflater.from(context);
this.context = context;
this.jsonObj = jsonObj;
JSONObject jObjectResult = null;
try {
jObjectResult = jsonObj.getJSONObject("Items");
this.listItems = jObjectResult.getJSONArray("Item");
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
final SharedPreferences pref= context.getApplicationContext ().getSharedPreferences("MyPref", context.MODE_PRIVATE);
final SharedPreferences.Editor editor = pref.edit();
try {
positionPrivate = position;
if(convertView == null){
convertView = layoutInflater.inflate (com.digitour.www.R.layout.activity_row,parent,false);
}
TextView textView = (TextView) convertView.findViewById (com.digitour.www.R.id.rowText);
textView.setText(listItems.getJSONObject(position).getString ("description"));
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try{
//Trying to get here the bound object
TextView tv = (TextView)v;
int id = tv.getId();
if (listItems != null){
JSONObject clickedItem = listItems.getJSONObject(positionPrivate); // positionPrivate always indexed to last item in a list
Intent intent = new Intent(context, DetailActivity.class);
context.startActivity(intent);
}
} catch (Exception e){
e.printStackTrace();
}
}
});
return convertView;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
非常感谢! – Radek