单击列表项时没有任何反应

时间:2016-01-30 06:35:09

标签: android performance listview android-fragments

我是android新手。当我点击listview项目时,没有任何反应。我检查了我的代码3次,但无法解决问题所在。我想在单击某个项目时,用户名将显示在下一个活动的文本视图中。我不知道这是什么问题。

这是我的listview项目代码

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="1dp">
<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/scrollView">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="10dp"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:background="#ffffff">

    <ImageView
        android:layout_width="380dp"
        android:layout_height="200dp"
        android:id="@+id/row_postPic"
        android:background="#dcdcdc"
        android:minHeight="50dp"
        android:scaleType="centerCrop"
        android:src="@drawable/url"
        android:layout_below="@+id/row_date"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="15dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="name"
        android:id="@+id/row_name"
        android:textSize="18dp"
        android:layout_alignTop="@+id/row_userid"
        android:layout_alignRight="@+id/row_date"
        android:layout_alignEnd="@+id/row_date"
        android:layout_alignLeft="@+id/row_userid"
        android:layout_alignStart="@+id/row_userid" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="date"
        android:id="@+id/row_date"
        android:textSize="16dp"
        android:layout_alignBottom="@+id/imageToDownload2"
        android:layout_alignRight="@+id/row_tittle"
        android:layout_alignEnd="@+id/row_tittle"
        android:layout_marginTop="60dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="tittle"
        android:id="@+id/row_tittle"
        android:layout_below="@+id/row_postPic"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="10dp"
        android:layout_marginRight="20dp"
        android:textSize="16dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="Category"
        android:id="@+id/row_cat"
        android:textSize="16dp"
        android:layout_above="@+id/row_postPic"
        android:layout_alignLeft="@+id/row_name"
        android:layout_alignStart="@+id/row_name" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="UserId"
        android:id="@+id/row_userid"
        android:textColor="#000000"
        android:textSize="18dp"
        android:layout_alignTop="@+id/imageToDownload2"
        android:layout_toRightOf="@+id/imageToDownload2"
        android:layout_toEndOf="@+id/imageToDownload2"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="20dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="PostId"
        android:id="@+id/row_postid"
        android:layout_alignParentTop="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:textColor="#000000"
        android:layout_marginTop="30dp" />

    <TextView
        android:layout_width="120dp"
        android:layout_height="40dp"
        android:text="Like"
        android:id="@+id/row_like"
        android:gravity="center"
        android:layout_below="@+id/row_tittle"
        android:layout_marginBottom="10dp"
        android:layout_marginTop="10dp" />

</RelativeLayout>
</ScrollView>
</RelativeLayout>

这里是列表适配器

public class PostAdapter extends BaseAdapter {
    Context context;
    ArrayList<Post> listData;

    public PostAdapter(Context context,ArrayList<Post> listData){
        this.context = context;
        this.listData = listData;
    }

    @Override
    public int getCount() {
        return listData.size();
    }

    @Override
    public Object getItem(int position) {
        return listData.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }
    class ViewHolder {
        private TextView tvlike,tvTittle,tvPostId,tvUseId,tvName,tvCat,tvDate;
    }
    @Override
    public View getView(int position, View view, ViewGroup viewGroup) {
        ViewHolder viewHolder = null;
        if(view == null){
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(R.layout.post_item,null);
            viewHolder = new ViewHolder();
            viewHolder.tvTittle = (TextView) view.findViewById(R.id.row_tittle);
            viewHolder.tvPostId = (TextView) view.findViewById(R.id.row_postid);
            viewHolder.tvUseId = (TextView) view.findViewById(R.id.row_userid);
            viewHolder.tvName = (TextView) view.findViewById(R.id.row_name);
            viewHolder.tvCat = (TextView) view.findViewById(R.id.row_cat);
            viewHolder.tvlike = (TextView) view.findViewById(R.id.row_like);
            viewHolder.tvDate = (TextView) view.findViewById(R.id.row_date);

            view.setTag(viewHolder);
        }else{
            viewHolder = (ViewHolder) view.getTag();
        }
        Post post = listData.get(position);
        String rpostid = post.getPost_id();
        String ruserid = post.getUser_id();
        String rname = post.getUser_name();
        String rcat = post.getPost_cat();
        String rlike = post.getLikes();
        String rdate = post.getPost_time();
        String rtittle = post.getPost_title();
        viewHolder.tvPostId.setText(rpostid);
        viewHolder.tvUseId.setText(ruserid);
        viewHolder.tvName.setText(rname);
        viewHolder.tvCat.setText("Category "+rcat);
        viewHolder.tvlike.setText("Toatal Likes "+rlike);
        viewHolder.tvDate.setText(rdate);
        viewHolder.tvTittle.setText(rtittle);

        return view;
    }
}

这是家庭活动

public class Home extends Fragment {

    ListView listView;
    PostAdapter adapter;
    TextView userId;
    ArrayList<Post> postArrayList;
    private SwipeRefreshLayout swipeRefreshLayout;
    DBHandler handler;
    View view;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.activity_post, container, false);
        listView = (ListView)  view.findViewById(R.id.listview);

        ConnectivityManager connectivityManager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if(networkInfo != null && networkInfo.isConnected()){
            new DataFetcherTask().execute();
        }else{
            Toast.makeText(getActivity(), "Internet Error", Toast.LENGTH_LONG).show();
        }

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Toast.makeText(getActivity(), "Item clicked : " + position, Toast.LENGTH_LONG).show();
                userId = (TextView)view.findViewById(R.id.row_userid);
                Intent i = new Intent(getActivity(), PostView.class);
                i.putExtra("userid", userId.getText().toString());
                startActivity(i);
            }
        });
        return view;

    }

    private class DataFetcherTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void... args) {
            String serverData = null;// String object to store fetched data from server
            // Http Request Code start
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet("http://xyz.lt/json.php");
            try {
                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                serverData = EntityUtils.toString(httpEntity);
                Log.d("response", serverData);
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            // Http Request Code end
            // Json Parsing Code Start
            try {
                postArrayList = new ArrayList<Post>();
                JSONObject jsonObject = new JSONObject(serverData);
                JSONArray jsonArray = jsonObject.getJSONArray("post");
                for (int i = 0; i < jsonArray.length(); i++) {

                    JSONObject jsonObjectPOST = jsonArray.getJSONObject(i);
                    String post_id = jsonObjectPOST.getString("post_id");
                    String user_id = jsonObjectPOST.getString("user_id");
                    String user_name = jsonObjectPOST.getString("user_name");
                    String post_title = jsonObjectPOST.getString("post_title");
                    String likes = jsonObjectPOST.getString("likes");
                    String post_cat = jsonObjectPOST.getString("post_cat");
                    String post_time = jsonObjectPOST.getString("post_time");
                    Post post = new Post();
                    post.setPost_id(post_id);
                    post.setUser_id(user_id);
                    post.setUser_name(user_name);
                    post.setPost_title(post_title);
                    post.setLikes(likes);
                    post.setPost_cat(post_cat);
                    post.setPost_time(post_time);
                    handler.addPost(post);// Inserting into DB
                }
            } catch (JSONException e) {
                e.printStackTrace();

            }
            //Json Parsing code end
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            ArrayList<Post> postList = handler.getAllPost();
            adapter = new PostAdapter(getActivity(), postList);
            listView.setAdapter(adapter);
        }
    }



    @Override
    public void onResume() {
        super.onResume();
        new DataFetcherTask().execute();
        ArrayList<Post> postList = handler.getAllPost();
        adapter = new PostAdapter(getActivity(), postList);
        listView.setAdapter(adapter);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        handler = new DBHandler(getActivity());
        new DataFetcherTask().execute();
    }
}

我希望当项目点击时,此处将打开新活动是新活动

public class PostView extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_post_view);
        TextView textView = (TextView) findViewById(R.id.textView3);

        Intent intent = getIntent();
        if (intent!=null) {
            String stringData= intent.getStringExtra("userid");
            textView.setText(stringData);
        }
    }
}

在这个项目中,当有些人点击listview项目时,它会将用户名的textview vaue传递给新意图但是作为列表项目clicklistner不能正常工作,所以我无法做到。

答案是:不要在Listview自定义项目中使用滚动视图。

3 个答案:

答案 0 :(得分:1)

这可能听起来不相关,但是你会从ScrollView删除list item layout来试用你的代码吗?因为click事件是由scrollView拍摄的,因此您的onItemCLickListener

似乎有问题

答案 1 :(得分:0)

据我所知,您已经在listview上应用onItemClick,这就是为什么它不起作用。 onitemclick和onClick没有合作更好的选项使用onClick代替onItemClick。

另一件事是在onCreateView中做其他事情并不好,因为它仅适用于View Inflate。从onCreateView中删除这行代码到onActivityCreated

 listView = (ListView)  view.findViewById(R.id.listview);

        ConnectivityManager connectivityManager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if(networkInfo != null && networkInfo.isConnected()){
            new DataFetcherTask().execute();
        }else{
            Toast.makeText(getActivity(), "Internet Error", Toast.LENGTH_LONG).show();
        }

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Toast.makeText(getActivity(), "Item clicked : " + position, Toast.LENGTH_LONG).show();
                userId = (TextView)view.findViewById(R.id.row_userid);
                Intent i = new Intent(getActivity(), PostView.class);
                i.putExtra("userid", userId.getText().toString());
                startActivity(i);
            }
        });

答案 2 :(得分:0)

try adding 

android:descendantFocusability="blocksDescendants"
in your main layout

eg.`
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:descendantFocusability="blocksDescendants"
android:paddingBottom="1dp">`

and set OnItemClickListener to your listView