如何通过ArrayAdapter将onClickListener设置为多个按钮[Android]

时间:2013-12-12 01:47:09

标签: android button onclick android-arrayadapter onclicklistener

如何通过ArrayAdapter将onClickListener设置为多个按钮?

请记住我需要按钮:  --A:杀死包含ArrayAdapter的Activity,并启动一个新的Activity。  --B:开始新的活动

以下是我的相关代码:

保持活动

public class MenuActivity extends FragmentActivity {

private LinkedList<Button> menuList;
private MenuButtonArrayAdapter menuButtonArrayAdapter;
private Button newGameButton, exitGameButton, continueGameButton;

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

    initialize();

    setUpMenu();
}

private void initialize()
{
    //Get references to fragments
    FragmentManager fragmentManager = getFragmentManager();
    MainMenuFragment menuFragment = (MainMenuFragment)fragmentManager.findFragmentById(R.id.MainMenuFragment);

    //Initialize list
    menuList = new LinkedList<Button>();

    //Create an ArrayAdapter to bind the List to ListViews
    menuButtonArrayAdapter = new MenuButtonArrayAdapter(this, R.layout.main_menu_button_layout, menuList);

    newGameButton = new Button(this);
    exitGameButton = new Button(this);
    newGameButton.setText("New game");
    exitGameButton.setText("Exit");

    menuFragment.setListAdapter(menuButtonArrayAdapter);
}

private void setUpMenu()
{

    menuList.add(newGameButton);
    menuList.add(exitGameButton);

    menuButtonArrayAdapter.notifyDataSetChanged();
}

@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, menu);
    return true;
}   

}

ArrayAdapter

 public class MenuButtonArrayAdapter extends ArrayAdapter<Button>{

private int resource;

public MenuButtonArrayAdapter(Context context, int resource, List<Button> objects) {
    super(context, resource, objects);
    this.resource = resource;
}

@Override
public View getView(int position, View convertView, ViewGroup parent)
{
    LinearLayout menuView;

    final String text = getItem(position).getText().toString();

    if(convertView == null)
    {
        menuView = new LinearLayout(getContext());
        String inflater = Context.LAYOUT_INFLATER_SERVICE;
        LayoutInflater layoutInflater = (LayoutInflater)getContext().getSystemService(inflater);
        layoutInflater.inflate(resource, menuView, true);
    }
    else menuView = (LinearLayout) convertView;

    Button b = (Button)menuView.findViewById(R.id.main_menu_button);
    b.setText(text);

    return menuView;
}

}

1 个答案:

答案 0 :(得分:0)

不推荐这种方式,但如果你坚持这样做,你可以设置标签到按钮,根据不同的标签,你可以轻松地分开两个或更多按钮。