我完全陷入了一些東西。我試圖在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