0

我很抱歉我的模棱两可的问题标题。我会尽力澄清我的问题。我尝试运行此代码来填充我的微调器:

public void UcitajPromenljive(int id)
{
    if(id==0)
    {
        //#SPISAK
    }
    if(id==1)
    {
        //#PRETRAGA
        try
        {
            Spinner oblasti = (Spinner) findViewById(R.id.spinnerOblasti);
            ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,R.array.oblasti, android.R.layout.simple_spinner_item);
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            oblasti.setAdapter(adapter);
        }
        catch(NullPointerException e)
        {
            Log.e("LOAD_TAG", e.getMessage());
        }
    }
    if(id==2)
    {
        //#OSTALO
    }
}

果然,我确实得到了 NPE,但我在一个类似的问题中发现问题出在代码的第一行。我的应用程序具有三个不同的选项卡,它们已被具体化为片段。因此,当我运行 findViewById(R.id.spinnerOblasti) 时,应用程序返回 NPE,因为我的布局只有 ActionBar 和一个相对布局作为其属性,并且相对布局通过填充

class MyTabListener implements ActionBar.TabListener
{
    public android.app.Fragment fragment;
    private Toast lol;
    public MyTabListener(android.app.Fragment fragment)
    {
        this.fragment = fragment;
    }

    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
        ft.remove(fragment);
        lol.cancel();
    }
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        lol = Toast.makeText(getApplicationContext(), tab.getText(), Toast.LENGTH_SHORT);
        lol.show();
        ft.replace(R.id.okvir, fragment);
        UcitajPromenljive(tab.getPosition());
    }

    public void onTabReselected(Tab tab, FragmentTransaction ft) {

    }
}

所以我的问题是 - 我如何解决 Spinner 问题,它是某个 .xml 文件的子文件,它会膨胀片段(选项卡)之一?随时要求澄清,我知道我所写的内容有些令人困惑。提前致谢。干杯

4

1 回答 1

0

存储您的片段视图以供参考,即将onCreateView()结果视图放入片段的全局范围,即

protected View mFragementView;

然后当您需要在片段布局中找到某些内容时,只需:

mFragmentView.findViewById(....);

例子:

public class MyFragment extends Fragment {

    protected View mFragmentView;

    @Override
    public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState ) {    
        mFragmentView = super.onCreateView( inflater, container, savedInstanceState );   
    }

    public void UcitajPromenljive(int id) {
        View v = mFragmentView.findViewById( R.id..... );
    }
}
于 2013-04-09T11:51:59.963 回答