按钮没有响应OnClickListener

时间:2016-01-15 04:58:43

标签: android android-button

我有一个activity从服务器加载数据。如果发生错误,我会显示Button重新加载/重试以加载数据。但是当我点击按钮时,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>

5 个答案:

答案 0 :(得分:2)

我发现了伙计们。感谢您的意见和建议。

在上面的LinearLayout中,我正在使用height widthmatch_parent作为RelativeLayout来包装我的两个include和将LinearLayout留在include之外。

我的RecyclerView文件包含match_parentheightwidth也有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> 文件,如下所示。

Deny from all
Allow from your.ip.address 

答案 1 :(得分: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"/>

调用按钮有两种方法,可以使用Listener调用它,也可以通过在按钮的xml中写一行来直接从xml调用按钮,即android:onClick =“方法的名称”

您在此处使用名称“onClick”

调用按钮方法
 @Override
public void onClick(View v) {
    switch (v.getId()){
        case R.id.tryAgainButton:
            sendJsonRequest(url);
            break;
    }
}

我还建议您将方法名称更改为任何其他名称,并在xml的onClick语句中定义该名称。

答案 2 :(得分:1)

  

您还可以在声明时在xml中定义onClick方法   按钮(或任何其他可点击的)组件。这样做时,你必须这样做   声明您想要的方法作为onClick方法。例如,像你一样   可以看到,我添加了一个带有值的android: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
 }

答案 3 :(得分:0)

您可以尝试使用并检查其是否正常工作

tryAgain.setOnClickListener(new View.OnClickListener(){

   @Override
  public void onClick(View v){

  sendJsonRequest(url);

}

});

答案 4 :(得分:0)

我对您的MyContactsActivity代码进行了一些更改,我的测试版本运行正常。

我已将alertHelpernetworkCheckersessionManagerappConfig注释掉,因为我无法访问该代码。

我还评论了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;
//        }
    }

按钮在此修剪后的代码中完美运行。

我建议尝试使用此代码,然后逐位添加每条注释行,因为这样可以轻松找到问题。