ListView点击事件无法使用SimpleAdapter。
我想在ListView的列表项中设置onclick事件。 现在,如何在列表视图中添加点击侦听器以打开活动的每一行?
我希望我已经正确解释了这个问题,对不起我的英语非常糟糕!谢谢大家。
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.drawable.LayerDrawable;
import android.os.AsyncTask;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v7.app.ActionBarDrawerToggle;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import android.graphics.drawable.Drawable;
public class NotificationsActivity extends AppCompatActivity {
DrawerLayout drawerLayout;
ActionBarDrawerToggle drawerToggle;
NavigationView navigation;
ListView notificationListView;
private int mNotificationsCount = 0;
private static final String NOTIFICATIONS_URL = "notification_url";
private static final String NOTIFICATION_COUNT_URL = "notification-count_url";
UserToken userToken = UserToken.getInstance();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notifications);
initInstances();
new FetchCountTask().execute();
notificationListView = (ListView)findViewById(R.id.notificationListView);
String usertoken = userToken.getValue();
if(usertoken == null) {
Intent intent = new Intent(NotificationsActivity.this, MainActivity.class);
startActivity(intent);
}
getJSON(NOTIFICATIONS_URL + "?token=" + usertoken);
}
private void getJSON(String url) {
class GetJSON extends AsyncTask<String, Void, String> {
ProgressDialog loading;
SimpleAdapter simpleAdapter;
@Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(NotificationsActivity.this, "Please Wait...",null,true,true);
}
@Override
protected String doInBackground(String... params) {
String uri = params[0];
BufferedReader bufferedReader = null;
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while((json = bufferedReader.readLine())!= null){
sb.append(json+"\n");
}
return sb.toString().trim();
}catch(Exception e){
return null;
}
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
try{
JSONObject emp = (new JSONObject(s)).getJSONObject("data");
if (emp != null) {
JSONArray notificationsArr = emp.getJSONArray("notifications");
if(notificationsArr.length() > 0) {
int lenArray = notificationsArr.length();
if (lenArray > 0) {
ArrayList<HashMap<String,String>> arrayList=new ArrayList<>();
for (int jIndex = 0; jIndex < lenArray; jIndex++) {
JSONObject innerObject = notificationsArr.getJSONObject(jIndex);
HashMap<String,String> hashMap=new HashMap<>();
//hashMap.put("image",Integer.toString(R.drawable.bell));
//hashMap.put("image",innerObject.getString("image"));
hashMap.put("body",innerObject.getString("body"));
hashMap.put("date",innerObject.getString("created_date"));
arrayList.add(hashMap);
}
//String[] from={"image","body","date"};//string array
String[] from={"body","date"};//string array
// int[] to={R.id.userPhoto,R.id.notificationBody,R.id.notificationDate};//int array of views id's
int[] to={R.id.notificationBody,R.id.notificationDate};//int array of views id's
SimpleAdapter simpleAdapter=new SimpleAdapter(NotificationsActivity.this,arrayList,R.layout.notification_row,from,to);
notificationListView.setAdapter(simpleAdapter);
/*notificationListView.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String cities = String.valueOf(parent.getItemAtPosition(position));
//Toast.makeText(Cities.this, cities, Toast.LENGTH_LONG).show();
}
});*/
}
}
}
}catch (Exception e) {
//e.printStackTrace();
Toast.makeText(NotificationsActivity.this, "Error: "+e.toString(), Toast.LENGTH_LONG).show();
}
}
}
GetJSON gj = new GetJSON();
gj.execute(url);
}
private void initInstances() {
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
drawerToggle = new ActionBarDrawerToggle(NotificationsActivity.this, drawerLayout, R.string.hello_world, R.string.hello_world);
drawerLayout.setDrawerListener(drawerToggle);
navigation = (NavigationView) findViewById(R.id.navigation_view);
navigation.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
int id = menuItem.getItemId();
switch (id) {
case R.id.navigation_item_1:
startActivity(new Intent(NotificationsActivity.this,ProfileActivity.class));
break;
case R.id.navigation_item_2:
startActivity(new Intent(NotificationsActivity.this,BlogsActivity.class));
break;
case R.id.navigation_item_3:
startActivity(new Intent(NotificationsActivity.this,GroupsActivity.class));
break;
case R.id.navigation_item_4:
startActivity(new Intent(NotificationsActivity.this,EventsActivity.class));
break;
case R.id.navigation_item_5:
userToken.setValue(null);
startActivity(new Intent(NotificationsActivity.this,MainActivity.class));
break;
case R.id.navigation_item_6:
startActivity(new Intent(NotificationsActivity.this,SettingsActivity.class));
break;
}
return false;
}
});
}
@Override
public void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
// Get the notifications MenuItem and
// its LayerDrawable (layer-list)
MenuItem item = menu.findItem(R.id.action_notifications);
LayerDrawable icon = (LayerDrawable) item.getIcon();
// Update LayerDrawable's BadgeDrawable
Utils.setBadgeCount(this, icon, mNotificationsCount);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (drawerToggle.onOptionsItemSelected(item))
return true;
// 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.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_notifications) {
//return true;
startActivity(new Intent(NotificationsActivity.this,NotificationsActivity.class));
}
return super.onOptionsItemSelected(item);
}
/*
Updates the count of notifications in the ActionBar.
*/
private void updateNotificationsBadge(int count) {
mNotificationsCount = count;
// force the ActionBar to relayout its MenuItems.
// onCreateOptionsMenu(Menu) will be called again.
invalidateOptionsMenu();
}
/*
Sample AsyncTask to fetch the notifications count
*/
class FetchCountTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
String usertokenss = userToken.getValue();
String uri = NOTIFICATION_COUNT_URL + "?token=" + usertokenss;
BufferedReader bufferedReader = null;
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while((json = bufferedReader.readLine())!= null){
sb.append(json+"\n");
}
return sb.toString().trim();
}catch(Exception e){
return null;
}
}
@Override
public void onPostExecute(String s) {
try {
JSONObject emp = (new JSONObject(s)).getJSONObject("data");
int notification_count = emp.getInt("notification_count");
updateNotificationsBadge(notification_count);
}catch (Exception e) {e.printStackTrace();}
}
}
}
答案 0 :(得分:2)
list.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Intent intent = new Intent(context, SendMessage.class);
String message = "abcpqr";
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
});
尝试这种方式。