2016-07-04 58 views
1

我想附加一個基本的onClick事件到設備的聯繫人列表。聯繫人列表已正確生成。我的代碼摘要如下:聯繫LoaderManager和AdapterView OnClick

public class Contacts extends AppCompatActivity implements 
LoaderManager.LoaderCallbacks<Cursor>, 
AdapterView.OnItemClickListener 
{ 
... 
     public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.contacts_list_view); 

     //initialise loader 
     getSupportLoaderManager().initLoader(CONTACTS_LOADER_ID, null, this); 

     mContactsList = (ListView) findViewById(android.R.id.list); 
     //Gets a CursorAdapter 
     mCursorAdapter = new SimpleCursorAdapter(
      this, 
      R.layout.contacts_list_item, 
      null, 
      FROM_COLUMNS, TO_IDS, 
      0); 
      //Sets the adapter for the ListView 
      mContactsList.setAdapter(mCursorAdapter); 

     } 
    } 

     //Followed by all the loader functions 

     public Loader<Cursor> onCreateLoader(int loaderId, Bundle args) {} 
     ... 
     public void onItemClick (AdapterView<?> parent, View view, int position, long id){ 
      Toast.makeText(this, 
      "hello world", 
      Toast.LENGTH_SHORT).show(); 
     } 

我的onItemClick不起作用。我首先必須創建一個OnItemClickListener的實例嗎?我試圖在onCreate方法內部和外部執行此操作,但都無法工作。

後來我試圖

mContactsList.setOnItemClickListener(new AdapterView.OnItemClickListener() { 

     public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
      Toast.makeText(getApplicationContext(), 
        "hello world", 
        Toast.LENGTH_SHORT).show(); 
     } 
    }); 
+0

你怎麼了clickListener設爲您的列表我的onCreate方法中的以下?您可能必須在onCreate:listView.setOnItemClickListener(this); – W0rmH0le

+0

嗨,我收到的錯誤是類'聯繫'必須聲明爲抽象的實現方法OnitemClick在OnItemClickListener –

+0

如果您設置偵聽器如下「mContactsList.setOnItemClickListener(new AdapterView.OnItemClickListener()」,您應該刪除「實現AdapterView .OnItemClickListener「從你的類聲明 – W0rmH0le

回答

0
public class Contacts extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor>, 

    public void onCreate(Bundle savedInstanceState) { 

     // Set screen content 
     setContentView(R.layout.main_screen_activity_layout); 

     // Find the list view 
     ListView mContactsList = findViewById(R.id.ID_OF_YOUR_LISTVIEW); 

     // Set the click listener 
     mContactsList.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
      public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
       Toast.makeText(getApplicationContext(), 
         "hello world", 
         Toast.LENGTH_SHORT).show(); 
      } 
     }); 

     // Create your adapter and set the adapter to your ListView via mContactsList.setAdapter(); 
    } 
+0

它的工作,但它沒有工作......當我點擊列表時,它並不是什麼都沒有。我將發佈我的onCreate方法的附加代碼 –