【问题标题】:onclick not working for listviewonclick 不适用于列表视图
【发布时间】:2014-05-01 20:04:18
【问题描述】:

仍在努力解决这个问题, 丢失指向android:descendantFocusability="blocksDescendants" 的帖子是罪魁祸首,但我似乎仍然无法为我的ListView 获得onclick 事件。

我应该指出,当我点击列表时,背景会变成蓝色,好像点击已注册,只是代码中没有任何反应..

来自我的 main.class:

    package com.whatsonwhere.app;

import android.app.ListActivity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentSender;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.UserHandle;
import android.util.Log;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Locale;

import static com.whatsonwhere.app.R.layout.results;


/** Called when the activity is first created. */

public class Home extends ListActivity {

    @Override
    //what happens when the app is launched this is the main proc...
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String[] pages = getResources().getStringArray(R.array.pages_array);

        setListAdapter(new ArrayAdapter<String>(this, results, pages));

        ListView lv = getListView();
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

         @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.e("Click", "Click");
                Intent myIntent = null;
                Toast.makeText(getApplicationContext(), "You Pushed a button.",
                        Toast.LENGTH_SHORT).show();
                if(((TextView) view).getText().equals("About")){
                    myIntent = new Intent(view.getContext(), About.class);
                }

                if(((TextView) view).getText().equals("Find events near me")){
                    myIntent = new Intent(view.getContext(), Results.class);
                }

                if(((TextView) view).getText().equals("Somewhere Else")){
                    myIntent = new Intent(view.getContext(), Search.class);
                }

                //if(((TextView) view).getText().equals("Switch to button mode")){
                //myIntent = new Intent(view.getContext(), ButtonPage.class);
                //}

                startActivity(myIntent);
            }
        });




        setContentView(R.layout.activity_home);
        //ok try and find the users location...
        //get Your Current Location
        LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        MyCurrentLoctionListener locationListener = new MyCurrentLoctionListener();
        //try and get GPS (Fine) Position
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);

        //also get location from network provider - speeds location aquisition up in case user is inside..
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
        //now we have the location wait for the update before it is displayed in onLocationChanged
        TextView textview=(TextView)findViewById(R.id.textView2);
        textview.setText("Searching...");

    }
        public class MyCurrentLoctionListener extends Context implements LocationListener {
        @Override
        public void onLocationChanged(Location location) {
            location.getLatitude();
            location.getLongitude();

            //String myLocation = "Latitude = " + location.getLatitude() + " Longitude = " + location.getLongitude();

            //make a log to see the results
            // Log.e("MY CURRENT LOCATION", myLocation);

            //maybe this is a good place to set the location string..
            //TextView textview = (TextView) findViewById(R.id.textView2);
            //textview.setText(myLocation);
            List<Address> addresses = null;
            try{
                Geocoder geocoder;
                geocoder = new Geocoder(this, Locale.getDefault());
                addresses=(geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1));

            }catch(IOException e){
                e.printStackTrace();
            }

            String address = addresses.get(0).getAddressLine(0);
            String city = addresses.get(0).getAddressLine(1);
            String country = addresses.get(0).getAddressLine(2);

//set the string to our new location

            TextView tv = (TextView) findViewById(R.id.textView2);
            tv.setText(address+"\n"+city+"\n"+country);


        }


            @Override
            public void onStatusChanged(String s, int i, Bundle bundle) {

            }

            @Override
            public void onProviderEnabled(String s) {

            }

            @Override
            public void onProviderDisabled(String s) {

            }


            @Override
            public AssetManager getAssets() {
                return null;
            }

            @Override
            public Resources getResources() {
                return null;
            }

            @Override
            public PackageManager getPackageManager() {
                return null;
            }

            @Override
            public ContentResolver getContentResolver() {
                return null;
            }

            @Override
            public Looper getMainLooper() {
                return null;
            }

            @Override
            public Context getApplicationContext() {
                return null;
            }

            @Override
            public void setTheme(int i) {

            }

            @Override
            public Resources.Theme getTheme() {
                return null;
            }

            @Override
            public ClassLoader getClassLoader() {
                return null;
            }

            @Override
            public String getPackageName() {
                return null;
            }

            @Override
            public ApplicationInfo getApplicationInfo() {
                return null;
            }

            @Override
            public String getPackageResourcePath() {
                return null;
            }

            @Override
            public String getPackageCodePath() {
                return null;
            }

            @Override
            public SharedPreferences getSharedPreferences(String s, int i) {
                return null;
            }

            @Override
            public FileInputStream openFileInput(String s) throws FileNotFoundException {
                return null;
            }

            @Override
            public FileOutputStream openFileOutput(String s, int i) throws FileNotFoundException {
                return null;
            }

            @Override
            public boolean deleteFile(String s) {
                return false;
            }

            @Override
            public File getFileStreamPath(String s) {
                return null;
            }

            @Override
            public File getFilesDir() {
                return null;
            }

            @Override
            public File getExternalFilesDir(String s) {
                return null;
            }

            @Override
            public File[] getExternalFilesDirs(String s) {
                return new File[0];
            }

            @Override
            public File getObbDir() {
                return null;
            }

            @Override
            public File[] getObbDirs() {
                return new File[0];
            }

            @Override
            public File getCacheDir() {
                return null;
            }

            @Override
            public File getExternalCacheDir() {
                return null;
            }

            @Override
            public File[] getExternalCacheDirs() {
                return new File[0];
            }

            @Override
            public String[] fileList() {
                return new String[0];
            }

            @Override
            public File getDir(String s, int i) {
                return null;
            }

            @Override
            public SQLiteDatabase openOrCreateDatabase(String s, int i, SQLiteDatabase.CursorFactory cursorFactory) {
                return null;
            }

            @Override
            public SQLiteDatabase openOrCreateDatabase(String s, int i, SQLiteDatabase.CursorFactory cursorFactory, DatabaseErrorHandler databaseErrorHandler) {
                return null;
            }

            @Override
            public boolean deleteDatabase(String s) {
                return false;
            }

            @Override
            public File getDatabasePath(String s) {
                return null;
            }

            @Override
            public String[] databaseList() {
                return new String[0];
            }

            @Override
            public Drawable getWallpaper() {
                return null;
            }

            @Override
            public Drawable peekWallpaper() {
                return null;
            }

            @Override
            public int getWallpaperDesiredMinimumWidth() {
                return 0;
            }

            @Override
            public int getWallpaperDesiredMinimumHeight() {
                return 0;
            }

            @Override
            public void setWallpaper(Bitmap bitmap) throws IOException {

            }

            @Override
            public void setWallpaper(InputStream inputStream) throws IOException {

            }

            @Override
            public void clearWallpaper() throws IOException {

            }

            @Override
            public void startActivity(Intent intent) {

            }

            @Override
            public void startActivity(Intent intent, Bundle bundle) {

            }

            @Override
            public void startActivities(Intent[] intents) {

            }

            @Override
            public void startActivities(Intent[] intents, Bundle bundle) {

            }

            @Override
            public void startIntentSender(IntentSender intentSender, Intent intent, int i, int i2, int i3) throws IntentSender.SendIntentException {

            }

            @Override
            public void startIntentSender(IntentSender intentSender, Intent intent, int i, int i2, int i3, Bundle bundle) throws IntentSender.SendIntentException {

            }

            @Override
            public void sendBroadcast(Intent intent) {

            }

            @Override
            public void sendBroadcast(Intent intent, String s) {

            }

            @Override
            public void sendOrderedBroadcast(Intent intent, String s) {

            }

            @Override
            public void sendOrderedBroadcast(Intent intent, String s, BroadcastReceiver broadcastReceiver, Handler handler, int i, String s2, Bundle bundle) {

            }

            @Override
            public void sendBroadcastAsUser(Intent intent, UserHandle userHandle) {

            }

            @Override
            public void sendBroadcastAsUser(Intent intent, UserHandle userHandle, String s) {

            }

            @Override
            public void sendOrderedBroadcastAsUser(Intent intent, UserHandle userHandle, String s, BroadcastReceiver broadcastReceiver, Handler handler, int i, String s2, Bundle bundle) {

            }

            @Override
            public void sendStickyBroadcast(Intent intent) {

            }

            @Override
            public void sendStickyOrderedBroadcast(Intent intent, BroadcastReceiver broadcastReceiver, Handler handler, int i, String s, Bundle bundle) {

            }

            @Override
            public void removeStickyBroadcast(Intent intent) {

            }

            @Override
            public void sendStickyBroadcastAsUser(Intent intent, UserHandle userHandle) {

            }

            @Override
            public void sendStickyOrderedBroadcastAsUser(Intent intent, UserHandle userHandle, BroadcastReceiver broadcastReceiver, Handler handler, int i, String s, Bundle bundle) {

            }

            @Override
            public void removeStickyBroadcastAsUser(Intent intent, UserHandle userHandle) {

            }

            @Override
            public Intent registerReceiver(BroadcastReceiver broadcastReceiver, IntentFilter intentFilter) {
                return null;
            }

            @Override
            public Intent registerReceiver(BroadcastReceiver broadcastReceiver, IntentFilter intentFilter, String s, Handler handler) {
                return null;
            }

            @Override
            public void unregisterReceiver(BroadcastReceiver broadcastReceiver) {

            }

            @Override
            public ComponentName startService(Intent intent) {
                return null;
            }

            @Override
            public boolean stopService(Intent intent) {
                return false;
            }

            @Override
            public boolean bindService(Intent intent, ServiceConnection serviceConnection, int i) {
                return false;
            }

            @Override
            public void unbindService(ServiceConnection serviceConnection) {

            }

            @Override
            public boolean startInstrumentation(ComponentName componentName, String s, Bundle bundle) {
                return false;
            }

            @Override
            public Object getSystemService(String s) {
                return null;
            }

            @Override
            public int checkPermission(String s, int i, int i2) {
                return 0;
            }

            @Override
            public int checkCallingPermission(String s) {
                return 0;
            }

            @Override
            public int checkCallingOrSelfPermission(String s) {
                return 0;
            }

            @Override
            public void enforcePermission(String s, int i, int i2, String s2) {

            }

            @Override
            public void enforceCallingPermission(String s, String s2) {

            }

            @Override
            public void enforceCallingOrSelfPermission(String s, String s2) {

            }

            @Override
            public void grantUriPermission(String s, Uri uri, int i) {

            }

            @Override
            public void revokeUriPermission(Uri uri, int i) {

            }

            @Override
            public int checkUriPermission(Uri uri, int i, int i2, int i3) {
                return 0;
            }

            @Override
            public int checkCallingUriPermission(Uri uri, int i) {
                return 0;
            }

            @Override
            public int checkCallingOrSelfUriPermission(Uri uri, int i) {
                return 0;
            }

            @Override
            public int checkUriPermission(Uri uri, String s, String s2, int i, int i2, int i3) {
                return 0;
            }

            @Override
            public void enforceUriPermission(Uri uri, int i, int i2, int i3, String s) {

            }

            @Override
            public void enforceCallingUriPermission(Uri uri, int i, String s) {

            }

            @Override
            public void enforceCallingOrSelfUriPermission(Uri uri, int i, String s) {

            }

            @Override
            public void enforceUriPermission(Uri uri, String s, String s2, int i, int i2, int i3, String s3) {

            }

            @Override
            public Context createPackageContext(String s, int i) throws PackageManager.NameNotFoundException {
                return null;
            }

            @Override
            public Context createConfigurationContext(Configuration configuration) {
                return null;
            }

            @Override
            public Context createDisplayContext(Display display) {
                return null;
            }


        }
//The next two are menu options...
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.home, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // 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();
        Toast.makeText(getApplicationContext(), "Not Implemented Yet.",
                Toast.LENGTH_SHORT).show();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

}

客户结果.xml

    <?xml version="1.0" encoding="utf-8"?>

    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:padding="10dp"
        android:textSize="18sp" >
    </TextView>

和我的主要活动

   <RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:background="#ffffff">
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imageView"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true"

        android:src="@drawable/logo" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="@string/l_location"
        android:id="@+id/textView"
        android:layout_alignParentTop="true"

        android:layout_toRightOf="@+id/imageView"
        android:layout_alignEnd="@+id/textView2"
        android:singleLine="false" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="@android:style/TextAppearance.DeviceDefault.Medium"
        android:text="@string/l_mylocation"
        android:id="@+id/textView2"

        android:layout_below="@+id/textView"
        android:layout_toRightOf="@+id/imageView"
        android:layout_alignParentEnd="true" />
    <ListView
        android:id="@id/android:list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"

        android:layout_below="@+id/imageView" />

</RelativeLayout>

还有一些 GPS 信息在后台运行,每次位置更改时都会更新 textview2

【问题讨论】:

  • 您可以发布您的活动代码吗?
  • 完成.. 主帖已更新

标签: android listview onclicklistener


【解决方案1】:

现在似乎可以工作了请检查AdapterViewAdapterView.OnItemClickListener Classes 的导入部分,

【讨论】:

  • 导入静态 com.whatsonwhere.app.R.layout.results;你是这个意思吗?
  • 如果您发现所有这些都导入错误,请将其更改为 import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener;import com.whatsonwhere.app.R;
  • 当我添加导入行时,它们显示为灰色,显示“未使用的导入语句”
【解决方案2】:

首先你有 3 个 If 行。这是完全不合适的。使用 if 和 else if。这很容易导致问题。

其次,您使用的是自定义ListView,这意味着每一行内部都有一个 TextView。行本身没有值,但每行中的对象。由于这个原因,onItemClick 总是导致 null,因为程序无法检索 TextView 的值。如果行中还有一个图像和一个按钮怎么办?当您单击一个项目时,程序如何知道您需要什么值?

看看this tutorial 以及它如何使用适配器类并实现对行的点击。这并不容易,但如果你遵循它,你可以在 10 分钟内创建一个自定义 ListView。

【讨论】:

  • 3 'if' 行可能不是好的编程习惯,(我正在从教程中尝试这个,以便在工作后整理代码)但我可以保证它们不是问题- 程序永远不会执行它们,我专门添加了日志行来尝试捕获发生的事件,但它没有。但是,我会看看你发布的替代教程,看看它是否对我有用。
  • 在教程的中心有一个显示onItemClick的空值的屏幕截图,您可以在下面找到解释。
  • 代码甚至没有走那么远,实际事件 public void onItemClick(AdapterView> parent, View view, int position, long id) { 永远不会被调用,没有'此时要处理的 null' 选择
  • 它是一个内置函数,每当您单击ListView 中的一行时都应该调用它,因为它位于listView.setOnItemClickListener 内部。几天前我已经尝试过了,同样的事情也发生在我身上。然后我创建了一个 Adapter 类,一切正常。
  • 好的,谢谢,我试试看。与我处理过的其他语言相比,学习曲线有点陡峭!
【解决方案3】:

试试这样的自定义布局。

<?xml version="1.0" encoding="utf-8"?>

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:focusable="false"
android:focusableInTouchMode="false"
android:padding="10dp"
android:textSize="18sp" >
</TextView>

您还必须从您的 listView 中删除 android:descendantFocusability="blocksDescendants",因为 The Doc 表示 blocksDescendants : The ViewGroup will block its descendants from receiving focus.

【讨论】:

    【解决方案4】:

    几周后,我发现我实施位置侦听器的方式导致了问题 - 此后我从头开始完全重写了代码,现在一切正常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-01
      • 2017-01-02
      • 2021-10-31
      • 2016-04-01
      • 2020-11-18
      • 2023-03-03
      • 2011-01-13
      相关资源
      最近更新 更多