2

Элемент ListView состоит из картинки и кнопки. Кликабельна только картинка, при нажатии на кнопку ничего не происходит. Как сделать чтобы клик был по всему элементу, то есть по кнопки и картинке одновременно? my_item.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:descendantFocusability="blocksDescendants"
>

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/button"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:focusable="false"
    android:focusableInTouchMode="false"
    android:layout_toLeftOf="@+id/imageArrow"
    android:layout_toStartOf="@+id/imageArrow"
    />

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/imageArrow"
    android:layout_alignTop="@+id/button"
    android:focusable="false"
    android:focusableInTouchMode="false"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:background="@drawable/r_arr" />

MainActivity.java

 public class MainActivity extends ListActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
//    setContentView(R.layout.activity_main);
   ListView listView = (ListView)findViewById(R.id.listView);
    String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
            "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
            "Linux", "OS/2" };
    MyCustomAdapter adapter = new MyCustomAdapter(this, values);
    setListAdapter(adapter);
    }

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, 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();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);
    String item = (String) getListAdapter().getItem(position);
    Toast.makeText(this, item + " selected", Toast.LENGTH_SHORT).show();
}
}

MyCustomAdapter.java

public class MyCustomAdapter extends ArrayAdapter<String> {
private final Activity context;
private final String[] names;

static class ViewHolder {
    public TextView myButton;
    public ImageView image;
}

public MyCustomAdapter(Activity context, String[] names) {
    super(context, R.layout.my_item, names);
    this.context = context;
    this.names = names;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View rowView = convertView;
    // reuse views
    if (rowView == null) {
        LayoutInflater inflater = context.getLayoutInflater();
        rowView = inflater.inflate(R.layout.my_item, null);
        // configure view holder
        ViewHolder viewHolder = new ViewHolder();
        viewHolder.myButton = (Button)rowView.findViewById(R.id.button);
        viewHolder.image = (ImageView)         rowView.findViewById(R.id.imageArrow);
        viewHolder.myButton.setFocusable(false);

        rowView.setTag(viewHolder);

    }

    // fill data
    ViewHolder holder = (ViewHolder) rowView.getTag();
    String s = names[position];
    String abs=Integer.toString(position + 1);
    holder.myButton.setText(s+ " number " + abs);


    holder.image.setImageResource(R.drawable.r_arr);
    return rowView;
}
}

2 ответа 2

2

Добавьте для Button и ImageView атрибут: android:clickable="false", он для так сказать "активных" элементов (кнопок, переключателей и т.п.) по умолчанию true и заставляет перехватывать клики.

1
  • Спасибо! Помогло, только пришлось в родительский лаяут добавить ещё android:descendantFocusability="blocksDescendants"
    – Mihailenko
    7 янв 2016 в 10:17
1

Скорее всего проблема вот в этих аттрибутах:

android:descendantFocusability="blocksDescendants"

android:focusable="false"

android:focusableInTouchMode="false"

Зачем они вам? Попробуйте их убрать.

2
  • Первоначально я пробывал без этих аттрибутов, эффект был тот же, потом добавил их, прочитав, что они в аналогичной ситуации решали проблему, но мне не помогло
    – Mihailenko
    6 янв 2016 в 17:29
  • @Mihailenko, а если назначать слушатель нажатий в адаптере, в методе getView? Убрав атрибуты помянутые и не используя обработчик нажатий в активити?
    – ЮрийСПб
    6 янв 2016 в 18:10

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.