Android 按钮控制器 class

Android Button Controller class

我正在尝试制作一个 class 来处理我制作的应用程序中的大多数常用按钮。 我只是不知道该怎么做。我用 ButtonPressed 方法创建了一个 class,它将执行每个按下的按钮的动作。 我尝试了几种方法,但我认为归根结底是我没有将视图直接传递给 class。有更好的方法吗? 感谢您的任何帮助。它给我的错误是一个 Nullpoint 引用。我认为这是因为不知道去哪里寻找风景。

此处的主要重点是允许此按钮控制器 class 通过仅调用被按下的按钮来处理每个 activity 共有的按钮。我不想每次更改每个 activity 中的某些内容时都继续复制和粘贴按钮控件。

这是按下的按钮class

public class ButtonControler extends AppCompatActivity {


public ButtonControler(){}

public void buttonPressed()
{
    //add the buttons contorls
    //if the top button is pushed get the promotion page
    final ImageButton promo = (ImageButton)findViewById(R.id.apivita);
    promo.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent getPromos = new Intent(v.getContext(),PromotionMain.class);
            startActivity(getPromos);
        }
    });
    //if the button 1  is pushed get the defulat webview page
    final ImageButton button1 = (ImageButton)findViewById(R.id.button1);
    button1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d("Button1: ", "Pressed");
            Intent button1Pressed = new Intent(v.getContext(),MyWebViewMain.class);
            startActivity(button1Pressed);
        }
    });


    //if the cart is pushed get the cart webview page
    final ImageButton cart = (ImageButton)findViewById(R.id.button2);
    cart.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d("Cart: ","Pressed");
            Intent myCart = new Intent(v.getContext(),Cart.class);
            startActivity(myCart);
        }
    });

    //if the button 3  is pushed get the defulat webview page
    final ImageButton button3 = (ImageButton)findViewById(R.id.button3);
    button3.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d("Button3: ","Pressed");
            Intent buttonPressed = new Intent(v.getContext(),MyWebViewMain.class);
            startActivity(buttonPressed);
        }
    });

    //if the button 4  is pushed get the defulat webview page
    final ImageButton button4 = (ImageButton)findViewById(R.id.button4);
    button4.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d("Button4: ","Pressed");
            Intent buttonPressed = new Intent(v.getContext(),MyWebViewMain.class);
            startActivity(buttonPressed);
        }
    });

    //if the Store list  is pushed get the defulat webview page
    final ImageButton storeList = (ImageButton)findViewById(R.id.button5);
    storeList.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d("StoreList: ","Pressed");
            Intent myStoreList = new Intent(v.getContext(),StoreList.class);
            startActivity(myStoreList);
        }
    });

    //if the Store list  is pushed get the notification
    final Button notification = (Button)findViewById(R.id.gcmlogo);
    notification.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d("Notificatiion: ","Pressed");
            Intent myNotification = new Intent(v.getContext(),GCMMainActivity.class);
            startActivity(myNotification);
        }
    });

    //if the Store list  is pushed get the notification
    final Button myPage = (Button)findViewById(R.id.mypage);
    myPage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d("MyPage: ","Pressed");
            //read the stored values
            String storedUser = CustomerPerferences.readString(getApplicationContext(), CustomerPerferences.USER_NAME, "");
            String storedPass =CustomerPerferences.readString(getApplicationContext(), CustomerPerferences.PASSWORD, "");
            //see if use has entered a username and password
            if(storedUser.equals("USER_NAME"))
            {
                Log.d("Loging in", "Go!");
                Intent goToLogin = new Intent(v.getContext(),LoginPage.class);
                startActivity(goToLogin);
            }else
            {

                Intent goToLogin = new Intent(v.getContext(),CustomerPage.class);
                goToLogin.putExtra("user_name", storedUser);
                startActivity(goToLogin);
            }

        }
    });

这是将使用按钮控制器的主要页面之一的示例 class

public class PromotionMain extends AppCompatActivity {

//gobal variables
  //these are where the paths will be stored
final ArrayList<String> pictureArray = new ArrayList<String>();
final ArrayList<String> pathArray = new ArrayList<String>();
final ArrayList<String> labelArray = new ArrayList<String>();
//Promotiion website
final String promos = myUrl;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.promotion_layout);

    //parse the JSON string
    //parse the JSON string
    JSONParser jp = new JSONParser();

    try {
        jp.parsesData(promos, pictureArray, pathArray, labelArray);
    } catch (IOException e) {
        e.printStackTrace();
    }
    ArrayList<ListItem> listData = getListData();

    final ListView listView = (ListView) findViewById(R.id.custom_list);
    listView.setAdapter(new CustomListAdapter(this, listData));
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        //here is a method to either send the user to the poduct page
        //or to the main page in the app
        //open a new activity and close this one down
        @Override
        public void onItemClick(AdapterView<?> a, View v, int position, long id) {
            ListItem promoData = (ListItem) listView.getItemAtPosition(position);
            //Toast.makeText(PromotionMain.this, "Selected :" + " " + promoData.getPathUrl(), Toast.LENGTH_LONG).show();
            //open up a new activity and send it to this site http://52.68.68.86/magento
            //lest open up the corrisponding webpage
            Intent reDirect = new Intent();
            reDirect.setAction(Intent.ACTION_VIEW);
            reDirect.addCategory(Intent.CATEGORY_BROWSABLE);
            //need to make sure that if it is not a url them do nothing in future rendtions
            //other wise it will crash the app
            reDirect.setData(Uri.parse(promoData.getPathUrl()));
            String newUrl = Uri.parse(promoData.getPathUrl()).toString();
            //check to see if there is a path for the promotion
            if (newUrl.contains("http")) {
                startActivity(reDirect);
            } else {
                //if not do nothing
                Log.d("Path URL: ", " is null");
            }

        }
    });

    //add the buttons contorls
   // buttonPressed();
    ButtonControler bc = new ButtonControler();
    bc.buttonPressed();
    //ButtonControler bc = new ButtonControler();
    //bc.pressed(promo,cart,storeList,button1,button3,button4,null);

}
private ArrayList<ListItem> getListData() {
    ArrayList<ListItem> listGetData = new ArrayList<ListItem>();


    //get the url for the image from the picture array list
    for (int i = 0; i < pictureArray.size(); i++) {
        ListItem imageData = new ListItem();
        imageData.setUrl(pictureArray.get(i));
        imageData.setPathUrl(pathArray.get(i));
        imageData.setLableTitle(labelArray.get(i));
        listGetData.add(imageData);

    }
    return listGetData;
}

如果你想在按下按钮时转到某个 activity 你可以做一些简单的事情,你可以向它添加任何动作甚至调用函数

public class ListGroupsActivity extends AppCompatActivity {

    Button profile = (Button) findViewById(R.id.GoToProfile);
    Button wall =(Button) findViewById(R.id.GoToWall);
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        profile.setOnClickListener(
                new Button.OnClickListener() {
                    public void onClick(View v) {
                        Intent intent = new Intent(v.getContext(), ProfileActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                        startActivity(intent);
                    }
                }
        );
        wall.setOnClickListener(
                new Button.OnClickListener() {
                    public void onClick(View v) {
                        Intent intent = new Intent(v.getContext(),WallActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                        startActivity(intent);
                    }
                }
        );
    }
}

首先改变这个:

public class ButtonControler extends AppCompatActivity

public class ButtonControler

第二次将 Activity 传递给 public void buttonPressed()

喜欢

public void buttonPressed(Activity activity)

然后把每个findViewById改成

final ImageButton promo = (ImageButton)activity.findViewById(R.id.apivita);

然后像这样从 activity 调用此方法

ButtonControler bc = new ButtonControler();
bc.buttonPressed(this);

您每次都在创建不同的 activity 并在其上调用 findViewById。哪个没有视图也没有开始。

简单地说,让PromotionMainclassextendsButtonControlerclass。而不是 AppCompatActivity。

按以下方式更改 ButtonControler

public class ButtonControler {

    Activity mActivity;

    public ButtonControler(Activity activity) {
        mActivity = activity;
    }

    public void buttonPressed() {
        //add the buttons contorls
        //if the top button is pushed get the promotion page
        final ImageButton promo = (ImageButton) mActivity.findViewById(R.id.apivita);
        promo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent getPromos = new Intent(v.getContext(), PromotionMain.class);
                mActivity.startActivity(getPromos);
            }
        });
        //if the button 1  is pushed get the defulat webview page
        final ImageButton button1 = (ImageButton) mActivity.findViewById(R.id.button1);
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("Button1: ", "Pressed");
                Intent button1Pressed = new Intent(v.getContext(), MyWebViewMain.class);
                mActivity.startActivity(button1Pressed);
            }
        });


        //if the cart is pushed get the cart webview page
        final ImageButton cart = (ImageButton) mActivity.findViewById(R.id.button2);
        cart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("Cart: ", "Pressed");
                Intent myCart = new Intent(v.getContext(), Cart.class);
                mActivity.startActivity(myCart);
            }
        });

        //if the button 3  is pushed get the defulat webview page
        final ImageButton button3 = (ImageButton) mActivity.findViewById(R.id.button3);
        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("Button3: ", "Pressed");
                Intent buttonPressed = new Intent(v.getContext(), MyWebViewMain.class);
                mActivity.startActivity(buttonPressed);
            }
        });

        //if the button 4  is pushed get the defulat webview page
        final ImageButton button4 = (ImageButton) mActivity.findViewById(R.id.button4);
        button4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("Button4: ", "Pressed");
                Intent buttonPressed = new Intent(v.getContext(), MyWebViewMain.class);
                mActivity.startActivity(buttonPressed);
            }
        });

        //if the Store list  is pushed get the defulat webview page
        final ImageButton storeList = (ImageButton) mActivity.findViewById(R.id.button5);
        storeList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("StoreList: ", "Pressed");
                Intent myStoreList = new Intent(v.getContext(), StoreList.class);
                mActivity.startActivity(myStoreList);
            }
        });

        //if the Store list  is pushed get the notification
        final Button notification = (Button) mActivity.findViewById(R.id.gcmlogo);
        notification.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("Notificatiion: ", "Pressed");
                Intent myNotification = new Intent(v.getContext(), GCMMainActivity.class);
                mActivity.startActivity(myNotification);
            }
        });

        //if the Store list  is pushed get the notification
        final Button myPage = (Button) mActivity.findViewById(R.id.mypage);
        myPage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("MyPage: ", "Pressed");
                //read the stored values
                String storedUser = CustomerPerferences.readString(mActivity.getApplicationContext(), CustomerPerferences.USER_NAME, "");
                String storedPass = CustomerPerferences.readString(mActivity.getApplicationContext(), CustomerPerferences.PASSWORD, "");
                //see if use has entered a username and password
                if (storedUser.equals("USER_NAME")) {
                    Log.d("Loging in", "Go!");
                    Intent goToLogin = new Intent(v.getContext(), LoginPage.class);
                    mActivity.startActivity(goToLogin);
                } else {

                    Intent goToLogin = new Intent(v.getContext(), CustomerPage.class);
                    goToLogin.putExtra("user_name", storedUser);
                    mActivity.startActivity(goToLogin);
                }

            }
        });


    }
}

目前不知道您的包名所以用 your.package.name.R

替换 R
final ImageButton promo = (ImageButton) mActivity.findViewById(R.id.apivita);

final ImageButton promo = (ImageButton) mActivity.findViewById(com.example.pagerview.R.id.apivita);