动态地向linearlayout添加按钮

时间:2012-08-22 20:41:54

标签: android android-layout button

我正在尝试将按钮添加到linearLayout:

public void populateAlarmLayout() {
        Log.d("Array", alarmButtons.size() + "");
        alarmLayout = (LinearLayout)findViewById(R.id.alarmlayout);
        for(int i = 0; i < alarmButtons.size(); i++) {
            selectedButton = new Button(this);
            selectedButton.setId(i+1);
            selectedButton.setWidth(150);
            selectedButton.setHeight(150);
            selectedButton.setTextSize(10);
            selectedButton.setText(alarmButtons.get(i));
            selectedButton.setOnClickListener(new ClickListener());
            selectedButton.setOnLongClickListener(new LongClickListener());
            alarmLayout.addView(selectedButton);
        }
    }

我在最后一行nullpointer收到alarmLayout.addView(selectedButton)例外alarmlayout alarm.xml中指定contentView,但我main_activity.xml的当前PagerAdapter设置为private class MyPagerAdapter extends PagerAdapter { public int getCount() { return 3; } public Object instantiateItem(View collection, int position) { LayoutInflater inflater = (LayoutInflater) collection.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); int resId = 0; switch (position) { case 0: resId = R.layout.main; break; case 1: resId = R.layout.music; break; case 2: resId = R.layout.alarm; break; } View view = inflater.inflate(resId, null); ((ViewPager) collection).addView(view, 0); return view; } } }}。我很确定这是问题所在,但我不知道如何解决它!

我正在使用{{1}},这也可能是问题所在。这是代码:

{{1}}

3 个答案:

答案 0 :(得分:0)

如果alarmlayout不在当前视图中,我相信您需要先对其进行充气才能添加任何视图。

alarmLayout = getLayoutInflater().inflate(R.id.alarmlayout);

答案 1 :(得分:0)

代码很好。据我所知,NullPointerException可能来自alarmLayout。 你可以调试你的应用程序并设置一对中断点来确认吗?

基于此,您能否检查一下资源的名称是否与xml中的外观完全相同?:

alarmLayout = (LinearLayout)findViewById(R.id.alarmlayout);

答案 2 :(得分:0)

我认为我遇到了同样的问题。我有一个GUI但无法在我的java文件中访问它。我还尝试通过初始化一个新的LinearLayout来实现。

但是,我尝试使用ViewGroup和之前设置的id,用于我的LinearLayout。

我的代码如下所示:

ViewGroup linearLayout = (ViewGroup) findViewById(R.id.llActOver);
Button btTest = new Button(this);
btTest.setText("Test Button");
linearLayout.addView(btTest);
相关问题