Android如何在ListView的列表项中设置onClick事件

Android如何在ListView的列表项中设置onClick事件,android,Android,ListView单击事件无法使用SimpleAdapter工作 我想在ListView的列表项中设置onclick事件。 现在,如何在listview上添加一个click侦听器来打开活动中的每一行 我希望我已经正确地解释了这个问题,我很抱歉我的英语很差!谢谢大家 import android.app.ProgressDialog; import android.content.Intent; import android.content.res.Configuration

ListView单击事件无法使用SimpleAdapter工作

我想在ListView的列表项中设置onclick事件。 现在,如何在listview上添加一个click侦听器来打开活动中的每一行

我希望我已经正确地解释了这个问题,我很抱歉我的英语很差!谢谢大家

    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();}
            }
        }
    }
导入android.app.ProgressDialog;
导入android.content.Intent;
导入android.content.res.Configuration;
导入android.graphics.drawable.LayerDrawable;
导入android.os.AsyncTask;
导入android.support.design.widget.NavigationView;
导入android.support.v4.widget.DrawerLayout;
导入android.support.v7.app.AppActivity;
导入android.os.Bundle;
导入android.view.Menu;
导入android.view.MenuItem;
导入android.support.v7.app.ActionBarDrawerToggle;
导入android.widget.ListView;
导入android.widget.simpledapter;
导入android.widget.Toast;
导入org.json.JSONArray;
导入org.json.JSONObject;
导入java.io.BufferedReader;
导入java.io.InputStreamReader;
导入java.net.HttpURLConnection;
导入java.net.URL;
导入java.util.ArrayList;
导入java.util.HashMap;
导入android.graphics.drawable.drawable;
公共类NotificationsActivity扩展了AppCompativeActivity{
抽屉布局抽屉布局;
ActionBarDrawerToggle抽屉切换;
导航视图导航;
ListView通知ListView;
私有int mNotificationsCount=0;
私有静态最终字符串通知\u URL=“通知\u URL”;
私有静态最终字符串通知\u COUNT\u URL=“NOTIFICATION-COUNT\u URL”;
UserToken UserToken=UserToken.getInstance();
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_通知);
initInstances();
新建FetchCountTask().execute();
notificationListView=(ListView)findViewById(R.id.notificationListView);
字符串usertoken=usertoken.getValue();
if(usertoken==null){
意向意向=新意向(NotificationsActivity.this,MainActivity.class);
星触觉(意向);
}
getJSON(通知URL+“?令牌=“+usertoken”);
}
私有void getJSON(字符串url){
类GetJSON扩展异步任务{
对话加载;
simpledapter simpledapter;
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
loading=ProgressDialog.show(NotificationsActivity.this,“请稍候…”,null,true,true);
}
@凌驾
受保护的字符串doInBackground(字符串…参数){
字符串uri=params[0];
BufferedReader BufferedReader=null;
试一试{
URL=新的URL(uri);
HttpURLConnection con=(HttpURLConnection)url.openConnection();
StringBuilder sb=新的StringBuilder();
bufferedReader=新的bufferedReader(新的InputStreamReader(con.getInputStream());
字符串json;
而((json=bufferedReader.readLine())!=null){
sb.append(json+“\n”);
}
使某人恢复原状;
}捕获(例外e){
返回null;
}
}
@凌驾
受保护的void onPostExecute(字符串s){
super.onPostExecute(s);
loading.dispose();
试一试{
JSONObject emp=(新的JSONObject)).getJSONObject(“数据”);
如果(emp!=null){
JSONArray notificationsArr=emp.getJSONArray(“通知”);
if(notificationsArr.length()>0){
int lenArray=notificationsArr.length();
如果(lenArray>0){
ArrayList ArrayList=新的ArrayList();
for(int jIndex=0;jIndexlist.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);
            }
        });