【问题标题】:onItemClicklistner(); does'nt work for Custom listView in androidonItemClicklistener();不适用于android中的自定义listView
【发布时间】:2016-10-12 21:25:38
【问题描述】:

我有一个自定义 listView.xml 有一个 listView 作为。

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@null" >

    <ListView
        android:id="@+id/searchList"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/txtSearchFor"
        android:background="@color/Black" >
    </ListView>

</RelativeLayout>

此列表视图包含一个 ImageView、2 个 TextView 和一个 RatingBar (item_list.XML),如下所示。

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <RelativeLayout
        android:id="@+id/rel_SearchLayout01"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" >

        <ImageView
            android:id="@+id/img_searchBookCoverPhoto"
            android:layout_width="70dp"
            android:layout_height="100dp"
            android:layout_margin="5dp"
            android:background="@drawable/rounded_image_borders"
            android:focusable="false"
            android:src="@drawable/book1" />

        <TextView
            android:id="@+id/txt_searchBookTitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignTop="@+id/img_searchBookCoverPhoto"
            android:layout_marginTop="10dp"
            android:layout_toRightOf="@+id/img_searchBookCoverPhoto"
            android:focusable="false"
            android:text="The Basic Doctrine Of Islam"
            android:textColor="@color/White"
            android:textSize="16sp" />

        <TextView
            android:id="@+id/txt_searchAutherName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/txt_searchBookTitle"
            android:layout_marginTop="2dp"
            android:layout_toRightOf="@+id/img_searchBookCoverPhoto"
            android:focusable="false"
            android:text="By: Andrew J Newman"
            android:textColor="@color/SkyBlue"
            android:textSize="14sp" />

        <RatingBar
            android:id="@+id/searchRatingbar"
            style="?android:attr/ratingBarStyleSmall"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/txt_searchAutherName"
            android:layout_marginTop="12dp"
            android:layout_toRightOf="@+id/img_searchBookCoverPhoto"
            android:focusable="false"
            android:isIndicator="false"
            android:numStars="5"
            android:rating="5"
            android:stepSize="1" />
    </RelativeLayout>

</RelativeLayout>
  • 我的问题是我有一个 Listview 的点击事件,如下所示

但它不起作用,我真的很惊讶,为什么会发生这种情况

你可以看到我也设置了这个

android:focusable="false"

对于我的自定义 listView 中的所有视图。

这里也是自定义适配器的代码。

public class BookSearchResultActivity extends Activity {

    static final String URL = "http://www.shiaislamiclibrary.com/requesthandler.ashx";
    static final String KEY_ITEM = "Book"; // parent node
    static final String KEY_BOOKAUTHOR = "BookAuthor";
    static final String KEY_BOOKTITLE = "BookTitle";
    static final String KEY_BOOKCODE = "BookCode";
    static final String KEY_BOOKIMAGE = "BookImage";

    ArrayList<String> BookTitle = new ArrayList<String>();
    ArrayList<String> BookCoverPhotos = new ArrayList<String>();
    ArrayList<String> BookAuther = new ArrayList<String>();
    ArrayList<String> ImageByte = new ArrayList<String>();
    ArrayList<Bitmap> bitmapArray = new ArrayList<Bitmap>();

    ListView lv;
    ListView listView;
    Activity act = this;

    LayoutInflater inflater = null;

    TextView txtSearchedKeywords;
    TextView txtSearchFor;
    TextView txtBooksCount;
    String keyWordsSearch;
    String language;

    URL bookImageURL = null;
    Bitmap bitMapImage = null;
    Context context = BookSearchResultActivity.this;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.book_search_layout);

        txtSearchedKeywords = (TextView) findViewById(R.id.txtKeyWordSearched);
        txtSearchFor = (TextView) findViewById(R.id.txtSearchFor);
        txtBooksCount = (TextView) findViewById(R.id.txtNmbrOfBooksFound);
        listView = (ListView) findViewById(R.id.searchList);

        Intent getInfoIntent = getIntent();
        keyWordsSearch = getInfoIntent.getStringExtra("SEARCH_KEYWORDS");
        language = getInfoIntent.getStringExtra("LANG");

        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        // checking for availbe internet Connection
        if (cm.getActiveNetworkInfo() != null
                && cm.getActiveNetworkInfo().isAvailable()
                && cm.getActiveNetworkInfo().isConnected()) {

            new UIThread().execute(URL, keyWordsSearch, language);

        }

        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
                    long arg3) {
                Toast.makeText(context, BookTitle.get(pos).toString(),
                        Toast.LENGTH_SHORT).show();
            }
        });
    }

    private class UIThread extends AsyncTask<String, Integer, String> {

        ProgressDialog progressDialog;

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            progressDialog = ProgressDialog.show(getParent(),
                    "Search in Progress...",
                    "This may Take a few seconds.\nPlease Wait...");

            txtSearchFor.setText("Searching in Progress...!");
            txtBooksCount.setVisibility(View.INVISIBLE);

        }

        @Override
        protected String doInBackground(String... params) {

            String URL = params[0];
            String searchKeywords = params[1];

            XMLParser parser = new XMLParser();
            String XMLString = parser.getXmlFromUrl(URL, searchKeywords,
                    language);
            // Log.i("XML Response", XMLString);

            Document doc = parser.getDomElement(XMLString);

            NodeList nl = doc.getElementsByTagName(KEY_ITEM);

            // looping through all item nodes <item>
            for (int i = 0; i < nl.getLength(); i++) {
                Element e = (Element) nl.item(i);

                BookTitle.add(parser.getValue(e, KEY_BOOKTITLE));
                BookCoverPhotos.add("http://shiaislamicbooks.com/books_Snaps/"
                        + parser.getValue(e, KEY_BOOKCODE) + "/1_thumb.jpg");
                BookAuther.add(parser.getValue(e, KEY_BOOKAUTHOR));
                Log.i("URLs", BookCoverPhotos.toString());
            }
            for (int i = 0; i < BookAuther.size(); i++) {

                try {
                    bookImageURL = new URL(BookCoverPhotos.get(i));
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                    Log.i("URL", "ERROR at image position" + i + "");
                }

                try {
                    bitMapImage = BitmapFactory.decodeStream(bookImageURL
                            .openConnection().getInputStream());
                    bitmapArray.add(bitMapImage);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    Log.i("BITMAP", "ERROR" + i);
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);

            progressDialog.dismiss();
            txtSearchFor.setText("Results For");
            txtSearchedKeywords.setText("\"" + keyWordsSearch + "\"");
            txtBooksCount.setVisibility(View.VISIBLE);
            txtBooksCount.setText(bitmapArray.size() + " Book(s) found");
            ImageAdapter adapter = new ImageAdapter(getBaseContext(), act);
            listView.setAdapter(adapter);

        }

    }

    public class ImageAdapter extends BaseAdapter {

        public ImageAdapter(Context c) {
            context = c;
        }

        // ---returns the number of images---
        public int getCount() {
            return bitmapArray.size();
        }

        public ImageAdapter(Context ctx, Activity act) {
            inflater = (LayoutInflater) act
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        // ---returns the ID of an item---
        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        // ---returns an ImageView view---
        public View getView(int position, View convertView, ViewGroup parent) {

            // ImageView bmImage;

            final ViewHolder holder;
            View vi = convertView;
            if (convertView == null) {
                vi = inflater.inflate(R.layout.list_style, parent, false);
                holder = new ViewHolder();
                holder.txt_BooksTitle = (TextView) vi
                        .findViewById(R.id.txt_searchBookTitle);

                holder.img_BookCoverPhoto = (ImageView) vi
                        .findViewById(R.id.img_searchBookCoverPhoto);
                holder.txt_BooksAuthor = (TextView) vi
                        .findViewById(R.id.txt_searchAutherName);

                holder.ratingBar = (RatingBar) vi
                        .findViewById(R.id.searchRatingbar);

                vi.setTag(holder);
            } else {

                holder = (ViewHolder) vi.getTag();
            }
            holder.txt_BooksTitle.setText(BookTitle.get(position) + "");
            holder.img_BookCoverPhoto.setImageBitmap(bitmapArray.get(position));
            holder.txt_BooksAuthor.setText(BookAuther.get(position) + "");
            holder.ratingBar.setRating(3);
            return vi;
        }
    }

    class ViewHolder {
        TextView txt_BooksTitle;
        TextView txt_BooksAuthor;
        ImageView img_BookCoverPhoto;
        RatingBar ratingBar;
    }
}

【问题讨论】:

  • 你也应该给出:android:focusableInTouchMode="false"
  • 你可以设置:listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
  • 对于 listView 还是对于 listView 内的视图?
  • 文本视图和图像视图
  • 这会做什么 listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

标签: android listview onitemclicklistener custom-lists


【解决方案1】:

请更新item_list.xml文件的以下代码,它将解决您的问题。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <RelativeLayout
        android:id="@+id/rel_SearchLayout01"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" >

        <ImageView
            android:id="@+id/img_searchBookCoverPhoto"
            android:layout_width="70dp"
            android:layout_height="100dp"
            android:layout_margin="5dp"
            android:src="@drawable/ic_launcher" />

        <TextView
            android:id="@+id/txt_searchBookTitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignTop="@+id/img_searchBookCoverPhoto"
            android:layout_marginTop="10dp"
            android:layout_toRightOf="@+id/img_searchBookCoverPhoto"
            android:text="The Basic Doctrine Of Islam"
            android:textSize="16sp" />

        <TextView
            android:id="@+id/txt_searchAutherName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/txt_searchBookTitle"
            android:layout_marginTop="2dp"
            android:layout_toRightOf="@+id/img_searchBookCoverPhoto"
            android:text="By: Andrew J Newman"
            android:textSize="14sp" />

        <RatingBar
            android:id="@+id/searchRatingbar"
            style="?android:attr/ratingBarStyleSmall"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/txt_searchAutherName"
            android:layout_marginTop="12dp"
            android:layout_toRightOf="@+id/img_searchBookCoverPhoto"
            android:numStars="5"
            android:rating="5"
            android:stepSize="1" />
    </RelativeLayout>

</RelativeLayout>

【讨论】:

  • 我试过这个,没有使用 android:focusable="false"。但它没有用。 Anuj 答案有效。谢谢您的回复。 @IGP
  • @QadirHussain 从 Ratingbar 中删除 android:isIndicator="false" 然后它可以在没有任何更改的情况下工作。
  • 我应该从自定义 listVIew 中的所有视图中删除 android:isIndicator="false" 吗?
  • @QadirHussain 仅来自 RatingBar 控件。
  • 是的,IGP 比 Anuj 的答案更好。非常感谢你。让我投票给你。 :P
【解决方案2】:

您可以做的其他选择是在您的getView() 中,您可以使用您的ConvertView 来实现OnclickListener 之类的

convertView.(new View.OnClickListener(){

     @Override
     public void onClick(View view) 
    {
      //write your code here
    }
});

请让我知道这个替代方案是否有效

public View getView(final int position, View convertView, ViewGroup parent)
    {

            if(convertView == null) /* Create a new row view */
            {
                convertView = inflater.inflate(R.layout.simplerow, null);
            }

        convertView.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    //your implementation.
                }
            }


    }

【讨论】:

  • 这应该在您的 getView() 方法中,在您的 Custom Adapter 中。
  • 在您的情况下,它将是 vi 而不是 convertView
【解决方案3】:

This 可能适合你。

如果你想为不同的视图组件设置不同的监听器,那么就这样做

sqView.ticker.setOnClickListener(new OnClickListener(){

                    @Override
                    public void onClick(View view) {
                        // TODO Auto-generated method stub
//write your code here
}
});

【讨论】:

    【解决方案4】:

    同时添加 机器人:可点击=“假” android:focusable="假"

    在您的 item_list.XML 中

    我认为问题会解决

    【讨论】:

      【解决方案5】:

      在您的主 Activity 类中实现 OnItemClickListener。

      public class BookSearchResultActivity extends Activity implement OnItemClickListener {
      
      //now implement unimplemented methods 
      //and 
      listView.setOnItemClickListener(this);
      }
      

      希望对你有帮助。

      【讨论】:

        【解决方案6】:

        在自定义 ListView 中的所有小部件的 xml 文件中使 false 可点击和聚焦

        【讨论】:

        • @Treycos 哪个政策这么说?
        • 你说得对,更多的是关于内容......今天是时候停止审查了
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多