1

Android OnItemClickListener가 작동하지 않습니다. 나는 이미 내 비슷한 문제에 대한 해결책을 찾을 수 없었던 비슷한 질문들을 연구했다.탐색 드로어에서 파편이로드되지 않음 클릭 리스너

Log.d ("TAG", "Item Click Working"); Logcat에하지만 새 프래그먼트를 열 수 없습니다.

아래 코드를 첨부합니다.

**MainActivity** 

import java.io.UnsupportedEncodingException; 
import java.util.ArrayList; 
import java.util.Iterator; 
import java.util.List; 
import org.json.JSONException; 
import org.json.JSONObject; 
import android.annotation.SuppressLint; 
import android.app.Activity; 
import android.app.Fragment; 
import android.app.FragmentManager; 
import android.content.Context; 
import android.content.res.Configuration; 
import android.content.res.TypedArray; 
import android.graphics.Color; 
import android.graphics.drawable.ColorDrawable; 
import android.os.Bundle; 
import android.support.v4.app.ActionBarDrawerToggle; 
import android.support.v4.widget.DrawerLayout; 
import android.util.Log; 
import android.view.LayoutInflater; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.view.ViewGroup; 
import android.widget.AdapterView; 
import android.widget.AdapterView.OnItemClickListener; 
import android.widget.BaseAdapter; 
import android.widget.ImageView; 
import android.widget.ListView; 
import android.widget.TextView; 
import android.widget.Toast; 
import com.android.volley.Cache; 
import com.android.volley.Cache.Entry; 
import com.android.volley.Request.Method; 
import com.android.volley.Response; 
import com.android.volley.VolleyError; 
import com.android.volley.VolleyLog; 
import com.android.volley.toolbox.JsonObjectRequest; 
import com.sri.vaavefeed.adapter.FeedListAdapter; 
import com.sri.vaavefeed.app.AppController; 
import com.sri.vaavefeed.data.FeedItem; 

public class MainActivity extends Activity implements OnItemClickListener 
{ 
    private static final String TAG = MainActivity.class.getSimpleName(); 
    private ListView listView; 
    private FeedListAdapter listAdapter; 
    private List<FeedItem> feedItems; 
    private String URL_FEED = "http://coherendz.net/vaavefeed1.json"; 
    int node_type; 
    FeedItem item; 
    private DrawerLayout mDrawerLayout; 
    private ListView mDrawerList; 
    private ActionBarDrawerToggle mDrawerToggle; 
    private ArrayList<NavDrawerItem> navDrawerItems; 
    private TypedArray navMenuIcons; 
    private NavDrawerListAdapter adapter; 

    // nav drawer title 
    private CharSequence mDrawerTitle; 

    // used to store app title 
    private CharSequence mTitle; 

    // slide menu items 
    private String[] navMenuTitles; 
    private myAdapter myadapter; 
    private int node_id; 
    private String comments_count; 
    private String like_count; 
    private String readable_date; 
    private String name; 
    private String description; 


    @SuppressLint("NewApi") 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 



     mTitle = mDrawerTitle = getTitle(); 
     navMenuTitles = getResources().getStringArray(R.array.Options); 

    // nav drawer icons from resources 
     navMenuIcons = getResources() 
       .obtainTypedArray(R.array.nav_drawer_icons); 

     listView = (ListView) findViewById(R.id.list); 
     mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout); 
     mDrawerList = (ListView) findViewById(R.id.drawerList); 
     mDrawerList.setItemsCanFocus(true); 
     mDrawerList.setOnItemClickListener(new SlideMenuClickListener()); 


     getActionBar().setHomeButtonEnabled(true); 
     getActionBar().setDisplayHomeAsUpEnabled(true); 


     feedItems = new ArrayList<FeedItem>(); 

     listAdapter = new FeedListAdapter(this, feedItems); 
     listView.setAdapter(listAdapter); 

     // These two lines not needed, 
     // just to get the look of facebook (changing background color & hiding the icon) 

     getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#3b5998"))); 
     getActionBar().setIcon( 
        new ColorDrawable(getResources().getColor(android.R.color.transparent))); 

     // We first check for cached request 
     Cache cache = AppController.getInstance().getRequestQueue().getCache(); 
     Entry entry = cache.get(URL_FEED); 
     if (entry != null) { 
      // fetch the data from cache 
      try { 
       String data = new String(entry.data, "UTF-8"); 
       try { 
        parseJsonFeed(new JSONObject(data)); 
       } catch (JSONException e) { 
        e.printStackTrace(); 
       } 
      } catch (UnsupportedEncodingException e) { 
       e.printStackTrace(); 
      } 

     } else { 
      // making fresh volley request and getting json 
      JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET, 
        URL_FEED, null, new Response.Listener<JSONObject>() { 

         @Override 
         public void onResponse(JSONObject response) { 
          VolleyLog.d(TAG, "Response: " + response.toString()); 
          if (response != null) { 
           parseJsonFeed(response); 
          } 
         } 
        }, new Response.ErrorListener() { 

         @Override 
         public void onErrorResponse(VolleyError error) { 
          VolleyLog.d(TAG, "Error: " + error.getMessage()); 
         } 
        }); 

      // Adding request to volley request queue 
      AppController.getInstance().addToRequestQueue(jsonReq); 
     } 


     mTitle = mDrawerTitle = getTitle(); 

     navDrawerItems = new ArrayList<NavDrawerItem>(); 

     // adding nav drawer items to array 
     // Home 
     navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1))); 
     // Find People 
     navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1))); 
     // Photos 
     navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1))); 
     // Communities, Will add a counter here 
     navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1), true, "22")); 
     // Pages 
     navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1))); 
     // What's hot, We will add a counter here 
     navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1), true, "50+")); 


     // Recycle the typed array 
     navMenuIcons.recycle(); 

     // setting the nav drawer list adapter 
     adapter = new NavDrawerListAdapter(getApplicationContext(), 
       navDrawerItems); 

     /* myadapter = new myAdapter(this);*/ 
      mDrawerList.setAdapter(adapter); 




     mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, 
       R.drawable.ic_drawer, //nav menu toggle icon 
       R.string.drawer_open, // nav drawer open - description for accessibility 
       R.string.drawer_close // nav drawer close - description for accessibility 
     ) 
     { 
      public void onDrawerClosed(View view) { 
       getActionBar().setTitle(mTitle); 
       // calling onPrepareOptionsMenu() to show action bar icons 
       invalidateOptionsMenu(); 
      } 

      public void onDrawerOpened(View drawerView) { 
       getActionBar().setTitle(mDrawerTitle); 
       // calling onPrepareOptionsMenu() to hide action bar icons 
       invalidateOptionsMenu(); 
      } 
     }; 
     mDrawerLayout.setDrawerListener(mDrawerToggle); 

     if (savedInstanceState == null) { 
      // on first time display view for first nav item 
      displayView(0); 
     } 
    } 

    /** 
    * Parsing json reponse and passing the data to feed view list adapter 
    * */ 
    private void parseJsonFeed(JSONObject response) { 

     @SuppressWarnings("rawtypes") 
     Iterator itr = response.keys(); 
     int i = 0; 

     try 
     {  
     while(itr.hasNext()) 

     { 
       String key = itr.next().toString(); 
       JSONObject entry = response.getJSONObject(key); 

       JSONObject phone = entry.getJSONObject("basic"); 
       name = phone.getString("title"); 
       description = phone.getString("description"); 
       node_type = phone.getInt("node_type"); 
       node_id = phone.getInt("node_id"); 
       JSONObject comments = entry.getJSONObject("comments"); 
       comments_count = comments.getString("count"); 
       JSONObject like = entry.getJSONObject("likes"); 
       like_count = like.getString("count"); 
       readable_date = phone.getString("readable_date"); 


       item = new FeedItem(); 
       item.setId(node_id); 
       item.setName(name);    
       item.setStatus(description); 
       item.setReadable_date(readable_date); 
       item.setComments_count(comments_count); 
       item.setLike_count(like_count); 

       i++; 


       // Image might be null sometimes 
       String image = response.isNull("image") ? null : response 
         .getString("image"); 


       // url might be null sometimes 
       String feedUrl = response.isNull("url") ? null : response 
         .getString("url"); 

       /*item.setUrl(feedUrl);*/ 
       item.setUrl(feedUrl); 
       feedItems.add(item); 
      } 

      // notify data changes to list adapater 
      listAdapter.notifyDataSetChanged(); 

     } 
     catch (JSONException e) 
     { 
      e.printStackTrace(); 
     } 
    } 
     /** 
     * Slide menu item click listener 
     * */ 
     private class SlideMenuClickListener implements 
       ListView.OnItemClickListener { 
      @Override 
      public void onItemClick(AdapterView<?> parent, View view, int position, 
        long id) 
      { // display view for selected nav drawer item 

       //Log.d("Kanth", "Item Click Working"); 
       Toast.makeText(MainActivity.this,navMenuTitles[position]+"was selected", Toast.LENGTH_LONG).show(); 
       displayView(position); 
      } 
     } 

     /** 
     * Diplaying fragment view for selected nav drawer list item 
     * */ 
     private void displayView(int position) { 
      // update the main content by replacing fragments 
      Fragment fragment = null; 
      switch (position) 
      { 
      case 0: 
       fragment = new HomeFragment(); 
       Bundle data = new Bundle(); 
       data.putInt("id", node_id); 
       data.putString("name", name); 
       data.putString("description", description); 
       data.putString("readable_date", readable_date); 
       data.putString("Comments_count", comments_count); 
       data.putString("Like_count", like_count); 
       fragment.setArguments(data); 
       Log.d("Kanth", "Item Click Working"); 
       break; 
      case 1: 
       fragment = new FindPeopleFragment(); 
       break; 
      case 2: 
       fragment = new PhotosFragment(); 
       break; 
      case 3: 
       fragment = new CommunityFragment(); 
       break; 
      case 4: 
       fragment = new PagesFragment(); 
       break; 
      case 5: 
       fragment = new WhatsHotFragment(); 
       break; 
      default: 
       break; 
      } 

      if (fragment != null) { 
       FragmentManager fragmentManager = getFragmentManager(); 
       fragmentManager.beginTransaction() 
         .replace(R.id.mainContent, fragment).commit(); 

       // update selected item and title, then close the drawer 
       mDrawerList.setItemChecked(position, true); 
       mDrawerList.setSelection(position); 
       setTitle(navMenuTitles[position]); 
       mDrawerLayout.closeDrawer(mDrawerList); 
      } 

      else 
      { 
       // error in creating fragment 
       Log.e("MainActivity", "Error in creating fragment"); 
      } 
      } 

      @Override 
      public boolean onCreateOptionsMenu(Menu menu) 
      { 
       getMenuInflater().inflate(R.menu.main, menu); 
       return true; 
      } 

      @Override 
      public boolean onOptionsItemSelected(MenuItem item) 
      { 
       // toggle nav drawer on selecting action bar app icon/title 
       if (mDrawerToggle.onOptionsItemSelected(item)) { 
        return true; 
       } 
       // Handle action bar actions click 
       switch (item.getItemId()) { 
       case R.id.action_settings: 
        return true; 
       default: 
        return super.onOptionsItemSelected(item); 
       } 
      } 

      /*** 
      * Called when invalidateOptionsMenu() is triggered 
      */ 
      @Override 
      public boolean onPrepareOptionsMenu(Menu menu) { 
       // if nav drawer is opened, hide the action items 
       boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList); 
       menu.findItem(R.id.action_settings).setVisible(!drawerOpen); 
       return super.onPrepareOptionsMenu(menu); 
      } 

      @Override 
      public void setTitle(CharSequence title) { 
       mTitle = title; 
       getActionBar().setTitle(mTitle); 
      } 

      /** 
      * When using the ActionBarDrawerToggle, you must call it during 
      * onPostCreate() and onConfigurationChanged()... 
      */ 

      @Override 
      protected void onPostCreate(Bundle savedInstanceState) 
      { 
       super.onPostCreate(savedInstanceState); 
       // Sync the toggle state after onRestoreInstanceState has occurred. 
       mDrawerToggle.syncState(); 
      } 

      @Override 
      public void onConfigurationChanged(Configuration newConfig) { 
       super.onConfigurationChanged(newConfig); 
       // Pass any configuration change to the drawer toggls 
       mDrawerToggle.onConfigurationChanged(newConfig); 
      } 

drawer_list_item.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="48dp" 
    android:clickable="false" 
    android:descendantFocusability="blocksDescendants" 
    android:focusable="false" 
    android:focusableInTouchMode="false" 
    > 

    <ImageView 
     android:id="@+id/icon" 
     android:layout_width="25dp" 
     android:layout_height="wrap_content" 
     android:layout_alignParentLeft="true" 
     android:layout_marginLeft="12dp" 
     android:layout_marginRight="12dp" 
     android:contentDescription="@string/desc_list_item_icon" 
     android:src="@drawable/ic_launcher" 
     android:layout_centerVertical="true" 
     android:clickable="false" 
     android:focusable="false" 
     android:focusableInTouchMode="false"/> 

    <TextView android:id="@+id/counter" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:background="@drawable/counter_bg" 
     android:layout_alignParentRight="true" 
     android:layout_marginRight="8dp" 
     android:textColor="#000000" 
     android:layout_centerHorizontal="true" 
     android:clickable="false" 
     android:focusable="false" 
     android:focusableInTouchMode="false"/> 

    <TextView 
     android:id="@+id/title" 
     android:layout_width="wrap_content" 
     android:layout_height="match_parent" 
     android:layout_alignParentTop="true" 
     android:layout_marginLeft="57dp" 
     android:layout_toRightOf="@+id/icon" 
     android:paddingRight="20dp" 
     android:paddingTop="5dp" 
     android:text="Hello" 
     android:layout_centerHorizontal="true" 
     android:textColor="#FFFFFF" 
     android:clickable="false" 
     android:focusable="false" 
     android:focusableInTouchMode="false"/> 

</RelativeLayout> 

activity_main.xml

<?xml version="1.0" encoding="utf-8"?> 
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:id="@+id/drawerLayout" 
android:layout_height="match_parent" 
android:layout_width="match_parent"> 

    <FrameLayout 
    android:id="@+id/mainContent" 
    android:layout_height="match_parent" 
    android:layout_width="match_parent">  
    </FrameLayout> 

    <!-- navigation drawer --> 
    <ListView 
     android:id="@+id/drawerList" 
     android:layout_width="240dp" 
     android:layout_height="match_parent" 
     android:divider="@null" 
     android:descendantFocusability="beforeDescendants" 
     android:listSelector="#FFFFFF" 
     android:background="#3b5998" 
     android:layout_gravity="left" />" 

<LinearLayout 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="vertical" > 

    <ListView 
     android:id="@+id/list" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:listSelector="#000000" 
     android:divider="@null" /> 

</LinearLayout> 
</android.support.v4.widget.DrawerLayout> 

이미지

+1

항목 클릭이 완벽하게 작동하므로 게시물에 대한 더 나은 주제를 찾으십시오. – greenapps

+0

토스트 메시지의 스크린 샷을 첨부 할 수 있습니까? – Srikanth

+0

조각에 전달할 "데이터"번들은 어디에 정의합니까? 또한 활동에 대한 레이아웃 파일을 첨부 할 수 있습니까? – brwngrldev

답변

0

다른 LinearLayout은 조각 콘텐츠를 숨기고 있습니다. 조각이로드되고 있습니다. 목록보기가 필요하지 않고 여분의 프레임 레이아웃을 제거하려면 선형 레이아웃에서 내용을로드해야합니다.

+0

선형 레이아웃으로로드를 시도했지만 제대로 작동하지 않았습니다. – Srikanth

+0

그것이 작동했습니다. 레이아웃 순서를 변경했습니다. drawlaylayout 아래에 linearlayout을 배치하고 그 아래에 다른 listview를 배치했습니다. – Srikanth

+0

대단한데, 내 대답이 도움이된다면 받아 들여주세요. 감사 – brwngrldev

0

귀하의 clickListener는 쓸모가 없습니다. ListView으로 설정하지 않았습니다. listView.setOnClickListener() 방법을 사용해야합니다. 이렇게 :

@SuppressLint("NewApi") 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 



    mTitle = mDrawerTitle = getTitle(); 
    navMenuTitles = getResources().getStringArray(R.array.Options); 

// nav drawer icons from resources 
    navMenuIcons = getResources() 
      .obtainTypedArray(R.array.nav_drawer_icons); 

    listView = (ListView) findViewById(R.id.list); 
    //////// Setting clickListener 
    listView.setOnItemClickListener(new OnItemClickListener() { 

      @Override 
     public void onItemClick(AdapterView<?> parent, View view, 
       int position, long id) { 
      // Here do whatever you want.. 
     } 
     }); 
    //////// 
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout); 
    mDrawerList = (ListView) findViewById(R.id.drawerList); 
    mDrawerList.setItemsCanFocus(true); 
    mDrawerList.setOnItemClickListener(new SlideMenuClickListener()); 
    ... 
+0

내가 위의 할 때이 오류가 나타납니다 .10-15 02 : 02 : 38.780 : (6394) : java.lang.RuntimeException : 활동을 시작할 수 없습니다 ComponentInfo {com ..../com .... MainActivity} : java.lang.RuntimeException : AdapterView에 대해 setOnClickListener를 호출하지 마십시오. 당신은 아마 대신 setOnItemClickListener – Srikanth

+0

listView에 대한 올바른 방법은 "setOnItemClickListener"이어야합니다 – Jorgesys

관련 문제