无法在片段内使用显示对话框功能?

时间:2018-12-26 14:18:19

标签: java android

简而言之,问题是我无法使用此功能显示对话框。

public class Page_6Fragment extends android.support.v4.app.Fragment {

    RecyclerView recyclerView;
    List<Customer> customers;
    CustomerAdapter adapter;
    View rootView;
    String TAG = "MainActivity - ";
    Context context;
    API api;
    Activity a;
    public static Page_6Fragment newInstance() {
        Page_6Fragment fragment = new Page_6Fragment();
        return fragment;
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
      rootView = inflater.inflate(R.layout.activity_customer, container, false);
        //   View rootView = inflater.inflate(R.xml.pref, container, false);
        //  Intent intent = new Intent(PreferenceDemoActivity.this,PrefsActivity.class);
        // startActivity(intent);

        this.context = getActivity();
        recyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
        customers = new ArrayList<>();
        adapter = new CustomerAdapter(context, customers);

        adapter.setLoadMoreListener(new CustomerAdapter.OnLoadMoreListener(){
            @Override
            public void onLoadMore() {
                recyclerView.post(new Runnable() {
                    @Override
                    public void run() {
                        int index = customers.size() - 1;
                      loadMore(index);
                    }
                });
                //Calling loadMore function in Runnable to fix the
                // java.lang.IllegalStateException: Cannot call this method while RecyclerView is computing a layout or scrolling error
            }
        });

        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(context));
        //recyclerView.addItemDecoration(new VerticalLineDecorator(2));
        recyclerView.setAdapter(adapter);
        api = ServiceGenerator.createService(API.class);
        load(0);
        return rootView;
    }
    private void load(int index){
        Call<List<Customer>> call = api.getCustomer(index);
        call.enqueue(new Callback<List<Customer>>(){
            @Override
            public void onResponse(Call<List<Customer>> call, Response<List<Customer>> response){
            // Toast.makeText(getActivity(), "tost "+response.body().get(0).post_writer, Toast.LENGTH_LONG).show();
               // Log.i("TRUE_TRUE","Yes"+response.body().get(0).title);
                if(response.isSuccessful()){
                    customers.addAll(response.body());
                    adapter.notifyDataChanged();
                    // Toast.makeText(MainActivity.this, "tost "+response.body().get(0).post_writer, Toast.LENGTH_LONG).show();
                }else{
                    Log.e(TAG," Response Error "+String.valueOf(response.code()));
                }
            }
            @Override
            public void onFailure(Call<List<Customer>> call, Throwable t) {
                Log.e(TAG," Response Error "+t.getMessage());
            }
        });
    }

    private void loadMore(int index){
        //add loading progress view
        customers.add(new Customer("load"));
        adapter.notifyItemInserted(customers.size()-1);
        Call<List<Customer>>call =  api.getCustomer(index);
        call.enqueue(new Callback<List<Customer>>(){
            @Override
            public void onResponse(Call<List<Customer>> call, Response<List<Customer>>response) {
                if(response.isSuccessful()){
                    // remove loading view .......
                    customers.remove(customers.size()-1);
                    List<Customer>result=response.body();
                    if(result.size()>0){
                        // add loaded data
                        customers.addAll(result);
                    }else{//result size 0 means there is no more data available at server
                        adapter.setMoreDataAvailable(false);
                        //telling adapter to stop calling load more as no more server data available
                        Toast.makeText(context,"No More Data Available",Toast.LENGTH_LONG).show();
                    }
                    adapter.notifyDataChanged();
                }else{
                    Log.e(TAG," Load More Response Error "+String.valueOf(response.code()));
                }
            }
            @Override
            public void onFailure(Call<List<Customer>>call,Throwable t) {
                Log.e(TAG," Load More Response Error "+t.getMessage());
            }
        });
    }

public void showDialog(){
    Dialog dialog = new Dialog(context);
    dialog.setCancelable(true);
    View view  = getActivity().getLayoutInflater().inflate(R.layout.layout, null);
    dialog.setContentView(view);
    dialog.show();
  }

}


// class to call function
package com.example.android.wacher.adapters;

import android.app.Dialog;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.android.wacher.R;
import com.example.android.wacher.activities.HomeActivity;
import com.example.android.wacher.fragments.Page_6Fragment;
import com.example.android.wacher.models.Customer;

import java.util.List;

/**
 * Created by cca on 23/12/2018.
 */

public class CustomerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    public final int TYPE_MOVIE = 0;
    public final int TYPE_LOAD = 1;

    static Context context;
    List<Customer> customers;
    OnLoadMoreListener loadMoreListener;
    boolean isLoading = false, isMoreDataAvailable = true;

    public CustomerAdapter(Context context, List<Customer> customers) {
        this.context = context;
        this.customers = customers;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        LayoutInflater inflater = LayoutInflater.from(context);
        if(viewType==TYPE_MOVIE){
            return new CustomerHolder(inflater.inflate(R.layout.row_movie,parent,false));
        }else{
            return new LoadHolder(inflater.inflate(R.layout.row_load,parent,false));
        }

    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {

        if(position>=getItemCount()-1 && isMoreDataAvailable && !isLoading && loadMoreListener!=null){
            isLoading = true;
            loadMoreListener.onLoadMore();
        }

        if(getItemViewType(position)==TYPE_MOVIE){
            ((CustomerHolder)holder).bindData(customers.get(position));

            if(((CustomerHolder)holder).buttonViewOption != null)((CustomerHolder)holder).buttonViewOption.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    // call function 
                  Page_6Fragment.newInstance().showDialog();
                }
            });
        }
    }




    @Override
    public int getItemViewType(int position) {
        if(customers.get(position).type.equals("movie")){
            return TYPE_MOVIE;
        }else{
            return TYPE_LOAD;
        }

    }

    @Override
    public int getItemCount(){

        return customers.size();
    }

    /* VIEW HOLDERS */

    static class CustomerHolder extends RecyclerView.ViewHolder{
        TextView tvTitle;
        TextView tvRating;
        Button buttonViewOption;

        public CustomerHolder(View itemView) {
            super(itemView);
            tvTitle=(TextView)itemView.findViewById(R.id.title);
            tvRating=(TextView)itemView.findViewById(R.id.rating);
            buttonViewOption = (Button) itemView.findViewById(R.id.textViewOptions);
        }

        void bindData(Customer cust){
           tvTitle.setText(cust.name);
           tvRating.setText(cust.title);
        }
    }

    static class LoadHolder extends RecyclerView.ViewHolder{
        public LoadHolder(View itemView) {
            super(itemView);
        }
    }

    public void setMoreDataAvailable(boolean moreDataAvailable) {
        isMoreDataAvailable = moreDataAvailable;
    }

    /* notifyDataSetChanged is final method so we can't override it
         call adapter.notifyDataChanged(); after update the list
    */

    public void notifyDataChanged(){
        notifyDataSetChanged();
        isLoading = false;
    }


    public interface OnLoadMoreListener{
        void onLoadMore();
    }

    public void setLoadMoreListener(OnLoadMoreListener loadMoreListener) {
        this.loadMoreListener = loadMoreListener;
    }
}

当我调用ShowDialog函数时,会发生错误(粘贴在下面。)

我不知道为什么此功能在Page_6Fragment类中不起作用。

Process: com.example.android.wacher, PID: 11335
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources$Theme android.content.Context.getTheme()' on a null object reference
at android.app.Dialog.<init>(Dialog.java:173)
at android.app.Dialog.<init>(Dialog.java:147)
at com.example.android.wacher.fragments.Page_6Fragment.showDialog(Page_6Fragment.java:153)
at com.example.android.wacher.adapters.CustomerAdapter$1.onClick(CustomerAdapter.java:70)
at android.view.View.performClick(View.java:5609)
at android.view.View$PerformClick.run(View.java:22259)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

1 个答案:

答案 0 :(得分:0)

您不能使用Page_6Fragment.newInstance().showDialog();。 方法public void showDialog()应该是private,因为它是句柄Context的引用。 在其他应使用的位置显示Dialog

public void showDialog(Context context){
   Dialog dialog = new Dialog(context);
   dialog.setCancelable(true);
   dialog.setContentView(R.layout.layout);
   dialog.show();
}

无需膨胀布局即可设置内容视图