2015-05-23 3 views
1

Я потратил несколько часов на проблему, и я все еще не могу понять это. Функция SetOnClickListener в приложении HotelOverviewFragment не запускается, когда я нажимаю элемент в моем ListView. Однако setOnClickListener работает с моим пользовательским адаптером (NowArrayAdapter).setOnClickListener не работает с пользовательским адаптером и пользовательским ListView

Мой вопрос: почему setOnClickListener не работает в HotelOverviewFragment (класс, где отображается ListView)?

Вот список того, что я пробовал:

  • Установка android:focusable="false", android:focusableInTouchMode="false", android:descendantFocusability="blocksDescendants" в hotel_row_layout.xml и fragment_hotel_overview.xml.

  • Установка android:clickable на true и false. Оба не работали.

  • Переход от реализации BaseAdapter к массиву Адаптер.

  • Я пробовал разные слушателей в HotelOverviewFragment: setOnClickListener, setOnItemClickListener, setOnItemSelectedListener и setOnTouchListener. К сожалению, ни один из них не работал для меня.

Вот мой код:

Пользовательский адаптер

public class NowArrayAdapter extends ArrayAdapter<String> { 

private Context context; 
private ArrayList<String> values; 
private Typeface typeface; 
private static Hashtable fontCache = new Hashtable(); 
private LayoutInflater inflater; 
private TextView item; 

public NowArrayAdapter(Context context, ArrayList<String> commandsList) { 
    super(context, R.layout.hotel_row_layout, commandsList); 
    this.context = context; 
    values = new ArrayList<String>(); 
    values.addAll(commandsList); 

    typeface = getTypeface(this.context, "fonts/Roboto-Light.ttf"); 
    inflater = LayoutInflater.from(this.context); 
} 

static Typeface getTypeface(Context context, String font) { 
    Typeface typeface = (Typeface)fontCache.get(font); 
    if (typeface == null) { 
     typeface = Typeface.createFromAsset(context.getAssets(), font); 
     fontCache.put(font, typeface); 
    } 
    return typeface; 
} 

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

    String myText = getItem(position); 

    if(convertView == null) { 
     convertView = inflater.inflate(R.layout.hotel_row_layout, parent, false); 

     item = (TextView) convertView.findViewById(R.id.maps_button); 
     item.setTypeface(typeface); 

     convertView.setTag(item); 
    } else { 
     item = (TextView) convertView.getTag(); 
    } 

    item.setText(myText); 
    //myListItem.descText.setTextSize(14); 

    convertView.setOnClickListener(new View.OnClickListener() { 
     // WORKS! 
     @Override 
     public void onClick(View view) { 
      Log.d("click", "Don't look at me!"); 
     } 
    }); 

    return convertView; 
    } 

} 

Фрагмент

public class HotelOverviewFragment extends Fragment { 
private static Hashtable fontCache = new Hashtable(); 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
} 

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState) { 
    View v = inflater.inflate(R.layout.fragment_hotel_overview, container, false); 
    ListView list = (ListView) v.findViewById(android.R.id.list); 

    // Set up listview and buttons 
    setUp(v, list); 

    // Inflate the layout for this fragment 
    return v; 
} 

static Typeface getTypeface(Context context, String font) { 
    Typeface typeface = (Typeface)fontCache.get(font); 
    if (typeface == null) { 
     typeface = Typeface.createFromAsset(context.getAssets(), font); 
     fontCache.put(font, typeface); 
    } 
    return typeface; 
} 

public void setUp(View v, ListView l){ 
    TextView address = (TextView) v.findViewById(R.id.content); 
    TextView header = (TextView) v.findViewById(R.id.header); 
    TextView hotelName = (TextView) v.findViewById(R.id.hotelName); 
    Typeface typeface = getTypeface(getActivity(), "fonts/Roboto-Light.ttf"); 

    address.setText("some street \nZipCode, City \nCountry \nEmail \nphoneNumber"); 
    address.setTypeface(typeface); 

    header.setText("Hotel info"); 
    header.setTypeface(typeface); 
    header.setTextSize(20); 

    hotelName.setText("Hotel name"); 
    hotelName.setTypeface(typeface); 

    // Set up button 
    ArrayList<String> n = new ArrayList<String>(); 
    n.add(0, "More info"); 

    // Show button 
    NowArrayAdapter adapter = new NowArrayAdapter(getActivity(), n); 

    l.setAdapter(adapter); 

    // THIS IS THE STUFF I'VE BEEN TRYING 
    try { 
     l.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       Log.d("click", "Success"); 
      } 
     }); 

     l.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
      @Override 
      public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
       Log.d("click", "Success"); 
      } 
     }); 

     l.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { 
      @Override 
      public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { 
       Log.d("click", "Success"); 
      } 

      @Override 
      public void onNothingSelected(AdapterView<?> parent) { 

      } 
     }); 

     l.setOnTouchListener(new View.OnTouchListener() { 
      @Override 
      public boolean onTouch(View v, MotionEvent event) { 
       Log.d("click", "Success"); 

       return false; 
      } 
     }); 
    }catch (Exception e){ 
     Log.d("click", e + ""); 
    } 
} 


} 

Layout XML из HotelOverviewFragment

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
tools:context="com.example" 
android:background="#ffebebeb"> 

<ScrollView 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"> 

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

     <LinearLayout 
      android:orientation="horizontal" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content"> 

      <RelativeLayout 
       android:layout_width="match_parent" 
       android:layout_height="match_parent"> 

       <ImageView 
        android:layout_width="fill_parent" 
        android:layout_height="200dp" 
        android:src="@drawable/banner" 
        android:id="@+id/hotelBanner" 
        android:layout_gravity="top" 
        android:adjustViewBounds="false" 
        android:scaleType="fitXY" /> 

       <TextView 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:textAppearance="?android:attr/textAppearanceLarge" 
        android:text="Hotelname" 
        android:id="@+id/hotelName" 
        android:gravity="center" 
        android:textSize="40dp" 
        android:layout_alignBottom="@+id/hotelBanner" 
        android:layout_alignParentRight="false" 
        android:layout_alignParentLeft="false" 
        android:textColor="#ffc4c4c4" 
        android:layout_marginBottom="5dp" /> 
      </RelativeLayout> 
     </LinearLayout> 

     <LinearLayout 
      android:orientation="vertical" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" 
      android:layout_marginLeft="10dp" 
      android:layout_marginRight="10dp" 
      android:layout_marginTop="10dp" 
      android:layout_marginBottom="0dp" 
      android:background="@drawable/header_card"> 

      <RelativeLayout 
       android:layout_width="match_parent" 
       android:layout_height="match_parent"> 

       <TextView 
        android:id="@+id/header" 
        android:layout_gravity="center_vertical" 
        android:layout_width="wrap_content" 
        android:layout_weight="1" 
        android:textColor="@android:color/primary_text_light" 
        android:layout_height="wrap_content" 
        android:text="Header" 
        android:layout_toRightOf="@+id/headerImage" 
        android:layout_centerVertical="true" /> 

       <ImageView 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:id="@+id/headerImage" 
        android:src="@drawable/ic_action_live_help" 
        android:layout_centerVertical="true" /> 
      </RelativeLayout> 

     </LinearLayout> 

     <LinearLayout 
      android:orientation="vertical" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" 
      android:layout_marginLeft="10dp" 
      android:layout_marginRight="10dp" 
      android:layout_marginTop="0dp" 
      android:layout_marginBottom="0dp" 
      android:background="@drawable/content_card"> 

      <TextView 
       android:id="@+id/content" 
       android:layout_gravity="left|center_vertical" 
       android:layout_width="fill_parent" 
       android:layout_weight="1" 
       android:textColor="@android:color/primary_text_light" 
       android:layout_height="wrap_content" 
       android:text="Content" 
       /> 
     </LinearLayout> 

     <LinearLayout 
      android:orientation="horizontal" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:layout_margin="5dp"> 

      <ListView android:id="@android:id/list" 
       android:layout_width="fill_parent" 
       android:layout_height="wrap_content" 
       android:clickable="true"/> 

     </LinearLayout> 

    </LinearLayout> 

</ScrollView> 

Обычай XML для элемента списке следует

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

<LinearLayout 
    android:orientation="vertical" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:layout_marginLeft="6dp" 
    android:layout_marginRight="6dp" 
    android:layout_marginTop="4dp" 
    android:layout_marginBottom="4dp" 
    android:background="@drawable/content_card"> 

    <RelativeLayout 
     android:layout_width="match_parent" 
     android:layout_height="match_parent"> 

     <TextView 
      android:id="@+id/maps_button" 
      android:layout_gravity="left|center_vertical" 
      android:layout_width="wrap_content" 
      android:layout_weight="1" 
      android:textColor="@android:color/primary_text_light" 
      android:layout_height="wrap_content" 
      android:layout_centerVertical="true" 
      android:layout_alignParentLeft="true" /> 

     <ImageView 
      android:src="@drawable/ic_action_arrow_right" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:id="@+id/imageView" 
      android:layout_alignParentTop="false" 
      android:layout_alignParentRight="true" 
      android:layout_alignParentBottom="false" 
      android:layout_centerVertical="true" 
      /> 

    </RelativeLayout> 
</LinearLayout> 

Спасибо заранее.

+0

Так что ничего не регистрируется при нажатии на ListView? –

+0

Вы пробовали это без вызова 'convertView.setOnClickListener()' в адаптере? –

+0

@EugeneH Nope кроме журнала из NowArrayAdapter – kkmah7

ответ

0

Благодаря предложению Даниэля Нуджента я получил его работу. Извлечение convertView.setOnClickListener() является частью ответа. Я думаю, что это блокировало других слушателей в HotelOverviewFragment.

Моя следующая ошибка заключалась в том, что я использовал setOnClickListener в ListView для тестирования. setOnClickListener следует использовать для кнопок, а не ListViews. Итак, после удаления setOnClickListener все остальные слушатели начали работать.

Спасибо за ваше время.