2016-01-15 4 views
1

У меня есть activity, который загружает данные с сервера. Если ошибка возникает, я показываю Button для перезагрузки/повторной загрузки для загрузки данных. Но onClickListener не отвечает, когда я нажимаю кнопку. Может кто-нибудь, пожалуйста, помогите мне с этим?Кнопка не отвечает на OnClickListener

Это моя деятельность

public class MyContactsActivity extends AppCompatActivity implements View.OnClickListener { 

    private RecyclerView recyclerView; 
    private ContactsAdapter adapter; 
    private NetworkChecker networkChecker; 
    private SessionManager sessionManager; 
    private AppConfig appConfig; 
    private RelativeLayout loading, retry; 
    private Button tryAgain; 
    AlertHelper alertHelper; 
    final ArrayList<Contact> contactArrayList = new ArrayList<>(); 
    String url; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_my_contacts); 
     Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
     setSupportActionBar(toolbar); 

     loading = (RelativeLayout) findViewById(R.id.loadingPanel); 
     retry = (RelativeLayout) findViewById(R.id.retry); 
     tryAgain = (Button) findViewById(R.id.tryAgainButton); 

     alertHelper = new AlertHelper(this); 
     networkChecker = new NetworkChecker(this); 
     sessionManager = new SessionManager(this); 
     appConfig = new AppConfig(); 

     String phone = sessionManager.getLoggedInUserPhone(); 
     url = appConfig.getApiUrlForSpecificContacts(phone); 

     tryAgain.setOnClickListener(this); 

     recyclerView = (RecyclerView) findViewById(R.id.contactsView); 
     adapter = new ContactsAdapter(getApplicationContext()); 
     recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext())); 

     sendJsonRequest(url); 
     recyclerView.setAdapter(adapter); 

     recyclerView.addOnItemTouchListener(
       new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() { 
        @Override public void onItemClick(View view, int position) { 
         TextView phone = (TextView) view.findViewById(R.id.contact_phone); 
         TextView name = (TextView) view.findViewById(R.id.contact_name); 
         Intent i = new Intent(getApplicationContext(), ContactProfileActivity.class); 
         i.putExtra("selected_user_phone", phone.getText()); 
         i.putExtra("selected_user_name", name.getText()); 
         startActivity(i); 
        } 
       }) 
     ); 

     FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); 
     fab.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) 
         .setAction("Action", null).show(); 
      } 
     }); 
     getSupportActionBar().setDisplayHomeAsUpEnabled(true); 
    } 

    private void sendJsonRequest(String url) { 
     if (networkChecker.networkAvailable()) { 
      loading.setVisibility(View.VISIBLE); 
      RequestQueue requestQueue = VolleySingleton.getsInstance().getmRequestQueue(); 

      StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() { 
       @Override 
       public void onResponse(String response) { 
        loading.setVisibility(View.GONE); 
        retry.setVisibility(View.GONE); 
        try { 
         JSONArray jsonArray = new JSONArray(response); 

         if(jsonArray != null){ 
          for (int i = 0; i < jsonArray.length(); i++) { 
           JSONObject currentContact = jsonArray.getJSONObject(i); 

           String name = currentContact.getString("name"); 
           String phone = currentContact.getString("phone"); 
           String city = currentContact.getString("city"); 
           String address = currentContact.getString("address"); 
           Boolean verified = currentContact.getBoolean("verified"); 

           Contact contact = new Contact(name, phone, city, address, verified); 

           contactArrayList.add(contact); 

          } 
          adapter.setContactsList(contactArrayList); 
         } 
         else{ 
          alertHelper.displayDialog("No Contacts Found."); 
         } 
        }catch (Exception e){ 
         retry.setVisibility(View.VISIBLE); 
        } 
       } 
      }, new Response.ErrorListener() { 
       @Override 
       public void onErrorResponse(VolleyError error) { 
        loading.setVisibility(View.GONE); 
        retry.setVisibility(View.VISIBLE); 
        if (error instanceof TimeoutError || error instanceof NoConnectionError) { 
         alertHelper.displayDialog(getString(R.string.connection_failed)); 
        } else { 
         alertHelper.displayDialog(error.toString()); 
        } 
       } 
      }); 

      requestQueue.add(stringRequest); 

     } else { 
      alertHelper.displayDialog(getString(R.string.network_not_available)); 
      retry.setVisibility(View.VISIBLE); 
     } 
    } 


    @Override 
    public void onClick(View v) { 
     switch (v.getId()){ 
      case R.id.tryAgainButton: 
       sendJsonRequest(url); 
       break; 
     } 
    } 
} 

И это мой XML макет

<?xml version="1.0" encoding="utf-8"?> 
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:fitsSystemWindows="true" 
    tools:context="com.pinesofts.quickcontact.MyContactsActivity"> 

    <android.support.design.widget.AppBarLayout 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:theme="@style/AppTheme.AppBarOverlay"> 

     <android.support.v7.widget.Toolbar 
      android:id="@+id/toolbar" 
      android:layout_width="match_parent" 
      android:layout_height="?attr/actionBarSize" 
      android:background="?attr/colorPrimary" 
      app:popupTheme="@style/AppTheme.PopupOverlay" /> 

    </android.support.design.widget.AppBarLayout> 

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

     <RelativeLayout 
      android:id="@+id/loadingPanel" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" 
      android:visibility="gone" 
      android:gravity="center" > 

      <ProgressBar 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:indeterminate="true" /> 
     </RelativeLayout> 

     <RelativeLayout 
      android:id="@+id/retry" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" 
      android:visibility="gone" 
      android:gravity="center" > 

      <TextView 
       android:id="@+id/retryText" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:text="@string/try_again_text"/> 

      <Button 
       android:id="@+id/tryAgainButton" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:layout_below="@id/retryText" 
       android:text="Try Again"/> 
     </RelativeLayout> 

    </LinearLayout> 

    <include layout="@layout/content_my_contacts" /> 

    <android.support.design.widget.FloatingActionButton 
     android:id="@+id/fab" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_gravity="bottom|end" 
     android:layout_margin="@dimen/fab_margin" 
     android:src="@android:drawable/ic_dialog_email" /> 

</android.support.design.widget.CoordinatorLayout> 
+0

приложить @Lalit –

+0

попробовать скриншот добавив интерактивными верно, когда вы сделаете вашу кнопку видимой –

+0

которой скриншоте мы говорим о @JigneshMavani –

ответ

0

вы можете попробовать использовать и проверить, если его работы

tryAgain.setOnClickListener(new View.OnClickListener(){ 

    @Override 
    public void onClick(View v){ 

    sendJsonRequest(url); 

} 

}); 
+0

Я тоже это пробовал. Это не работает. –

+0

Может случиться так, что ваша кнопка находится под любым видом, поэтому ее невозможно определить щелчок ..... Попробуйте изменить положение кнопки и проверить, работает ли она. – Nitesh

+0

Вы можете увидеть мой «макет xml» и как все будет размещено. Можете ли вы предложить мне, как я могу это сделать? –

1

В файле xml добавьте эту строку к своей кнопке android: onClick = "onClick", где onClick в двойных кавычках - это имя метода в вашей активности, которое вызывается при нажатии кнопки.

<Button 
      android:id="@+id/tryAgainButton" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_below="@id/retryText" 
      android:text="Try Again" 
      android:onClick="onClick"/> 

Есть два способа вызова кнопки, либо вызвать его Слушатель или вызвать кнопку непосредственно из XML, написав строку в баттоне XML т.е. андроиде: OnClick = «имя методы»

вы вызываете метод кнопки здесь с именем «OnClick»

@Override 
public void onClick(View v) { 
    switch (v.getId()){ 
     case R.id.tryAgainButton: 
      sendJsonRequest(url); 
      break; 
    } 
} 

Я также предлагаю вам изменить имя метода на любое другое имя и определить, что имя в операторе OnClick из XML.

+0

yes onClick - это имя метода, но он не определяет имя в xml, что является вторым способом вызова кнопки. – Andrain

+0

Это не работает, ребята, помогите мне, пожалуйста. –

+0

ok напишите оператор журнала внутри метода кнопки. Log.e («btn clicked», «yes»); и проверьте, печатается ли эта строка при нажатии кнопки – Andrain

1

Вы также можете определить метод onClick в xml при объявлении кнопки (или любого другого кликабельного) компонента. При этом вы должны объявить метод, который вы хотите как метод onClick. Например, как вы видите , я добавил андроид: атрибут onClick со значением clickFuncTion.

<Button 
     android:id="@+id/tryAgainButton" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:onClick="clickFuncTion" 
     android:text="Try Again" /> 

Тогда

public void clickFuncTion(View view){ 

    Toast.makeText(MyContactsActivity.this, "Button Clicked", Toast.LENGTH_SHORT).show(); 
    // Add your staff 
} 
+0

На самом деле проблема в том, что кнопка даже не реагирует на событие click, поэтому я думаю, что это не решение. –

+0

@LalitThapa Позвольте мне подтвердить, когда вы использовали этот подход. Тост стрелял или нет? –

+0

@LalitThapa Вы ​​должны добавить Break Point –

0

Я сделал некоторые изменения в свой код MyContactsActivity и моя тестовая версия работает отлично.


Я закомментирована ваш alertHelper, networkChecker, sessionManager, appConfig, потому что не имеют доступа к этому коду.

Я также прокомментировал все настройки вашего recyclerView.

protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_my_contacts); 
     Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
     setSupportActionBar(toolbar); 

     retry = (RelativeLayout) findViewById(R.id.retry); 
     tryAgain = (Button) findViewById(R.id.tryAgainButton); 

//  alertHelper = new AlertHelper(this); 
//  networkChecker = new NetworkChecker(this); 
//  sessionManager = new SessionManager(this); 
//  appConfig = new AppConfig(); 

//  String phone = sessionManager.getLoggedInUserPhone(); 
//  url = appConfig.getApiUrlForSpecificContacts(phone); 

     tryAgain.setOnClickListener(this); 

//  recyclerView = (RecyclerView) findViewById(R.id.contactsView); 
//  adapter = new ContactsAdapter(getApplicationContext()); 
//  recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext())); 

     String url = "unused"; 
     sendJsonRequest(url); 
//  recyclerView.setAdapter(adapter); 

//  recyclerView.addOnItemTouchListener(
//    new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() { 
//     @Override 
//     public void onItemClick(View view, int position) { 
//      TextView phone = (TextView) view.findViewById(R.id.contact_phone); 
//      TextView name = (TextView) view.findViewById(R.id.contact_name); 
//      Intent i = new Intent(getApplicationContext(), ContactProfileActivity.class); 
//      i.putExtra("selected_user_phone", phone.getText()); 
//      i.putExtra("selected_user_name", name.getText()); 
//      startActivity(i); 
//     } 
//    }) 
//  ); 

     FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); 
     fab.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) 
         .setAction("Action", null).show(); 
      } 
     }); 
     getSupportActionBar().setDisplayHomeAsUpEnabled(true); 
    } 

Я изменил ваш sendJsonRequest просто отобразить расположение и onClick показать Toast.

private void sendJsonRequest(String url) { 
     retry.setVisibility(View.VISIBLE); 
    } 


    @Override 
    public void onClick(View v) { 
     Toast.makeText(this, "Works!", Toast.LENGTH_SHORT).show(); 

//  switch (v.getId()) { 
//   case R.id.tryAgainButton: 
//    sendJsonRequest(url); 
//    break; 
//  } 
    } 

Кнопка отлично работает в этом урезана код.

Я предлагаю попробовать этот код, а затем добавить каждую прокомментированную строку пополам, поскольку это позволит легко найти проблему.

+1

Я попробую. Спасибо за ваши усилия. –

2

Я понял это, ребята. Благодаря вашим комментариям и предложениям.

В layout file выше, что я делаю это с помощью LinearLayout с height и width, как match_parent обернуть два RelativeLayout и оставляя include вне LinearLayout.

Мой файл содержит includeRecyclerView который также имеет match_parent на обоих height и width.

В связи с этим RecyclerView был на вершине моего RelativeLayout, который содержит мои Button. Поэтому я даже не смог щелкнуть мой Button.

Я изменил свой файл xml, как показано ниже, и он работает.

<?xml version="1.0" encoding="utf-8"?> 
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:fitsSystemWindows="true" 
    tools:context="com.pinesofts.quickcontact.MyContactsActivity"> 

    <android.support.design.widget.AppBarLayout 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:theme="@style/AppTheme.AppBarOverlay"> 

     <android.support.v7.widget.Toolbar 
      android:id="@+id/toolbar" 
      android:layout_width="match_parent" 
      android:layout_height="?attr/actionBarSize" 
      android:background="?attr/colorPrimary" 
      app:popupTheme="@style/AppTheme.PopupOverlay" /> 

    </android.support.design.widget.AppBarLayout> 

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

     <RelativeLayout 
      android:id="@+id/loadingPanel" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" 
      android:visibility="gone" 
      android:gravity="center"> 

      <ProgressBar 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:indeterminate="true" /> 
     </RelativeLayout> 

     <RelativeLayout 
      android:id="@+id/retry" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" 
      android:visibility="gone" 
      android:gravity="center"> 

      <TextView 
       android:id="@+id/retryText" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:text="@string/try_again_text" 
       android:layout_centerVertical="true" 
       android:layout_centerHorizontal="true" /> 

      <Button 
       android:id="@+id/tryAgainButton" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:gravity="center|center_vertical" 
       android:text="Try Again" 
       android:layout_below="@+id/retryText" 
       android:layout_centerHorizontal="true" /> 
     </RelativeLayout> 

     <include layout="@layout/content_my_contacts" /> 

    </LinearLayout> 

    <android.support.design.widget.FloatingActionButton 
     android:id="@+id/fab" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_gravity="bottom|end" 
     android:layout_margin="@dimen/fab_margin" 
     android:src="@android:drawable/ic_dialog_email" /> 

</android.support.design.widget.CoordinatorLayout> 
+0

Охх. Рад это видеть. Счастливое кодирование –

Смежные вопросы