findViewById不在片段内的静态函数中工作

时间:2012-11-14 08:32:51

标签: java android android-fragments

在我的Android应用程序中,我有一个fragment-fragment1。在那个片段里面,我有一个静态函数'function1'。我试图用静态函数定义一个buttton,

button=(Buton)getActivity().findViewById(R.id.button1);

但Eclipse抛出了一个错误,例如“无法从Fragment类型中对非静态方法getActivity()进行静态引用”。我做错了什么?我需要这个function1是静态的,所以我可以从另一个类调用它。我的意思是,当我选择一个特定的片段时,我必须从主活动填充列表视图。

片段1 =>

public class Fragment1 extends Fragment{


public static String feedurl="http://www.abcd.com/en/rssfeeds/1_2_3_5/latest/rss.xml";
static String URL = "";
static final String KEY_HEAD = "item"; // parent node
static final String KEY_DATE = "pubDate";
public static String headflag="";
int f=0;
static Button button;
    HeadlinesAdapter adapter;
    private TextView mMessageView;
private Button mClearButton;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View v = inflater.inflate(R.layout.first_fragment, container, false);


    return v;
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);



    function1();
    populate_listview();

    }


 public static void function1()
 {


     URL="http://www.abcd.com/en/rssfeeds/1_2_3_5/latest/rss.xml";
     ArrayList<HashMap<String, String>> newsList = new ArrayList<HashMap<String, String>>();

    XMLParser parser = new XMLParser();
    String xml = parser.getXmlFromUrl(URL);
    Document doc = parser.getDomElement(xml);
    NodeList nl = doc.getElementsByTagName(KEY_HEAD);
    NodeList itemLst = doc.getElementsByTagName("item");
    String MarqueeStr="";

    for (int i = 0; i < nl.getLength(); i++) {
        HashMap<String, String> map = new HashMap<String, String>();
        Element e = (Element) nl.item(i);
                    newsList.add(map);


 }
    button=(Buton)getActivity().findViewById(R.id.button1);;// Here it shows error.
    adapter=new Adapter1(getActivity(), newsList);        
            list.setAdapter(adapter);

  }

}

我的主要活动是,

ViewpagerActivity =&GT;

public class ViewPagerActivity extends FragmentActivity {

    private ViewPager mViewPager;
    private MessageLoader mLoader;
    private Button mSenderButton, mReceiverButton;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        // We get UI references
        mViewPager = (ViewPager) findViewById(R.id.viewPager);
        mSenderButton = (Button) findViewById(R.id.sender_button);
        mReceiverButton = (Button) findViewById(R.id.receiver_button);
        // We set pager adapter
        mViewPager.setAdapter(new MyAdapter(this));
        // We set receiver button listener


        mViewPager.setOnPageChangeListener(new OnPageChangeListener() {


            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) 
            {

            }

            int i=0;
            public void onPageSelected(int position) {
                   if(position==0){

                   }else if(position==1 && i==0){
                       Fragment1.function1(); // Here Iam calling function1

                       i++;
                   }

            }


            public void onPageScrollStateChanged(int state) {

            }
            });

        mReceiverButton.setOnClickListener(new OnClickListener() {          

            public void onClick(View v) {
                mViewPager.setCurrentItem(0);
            }
        });
        // We set sender button listener
        mSenderButton.setOnClickListener(new OnClickListener() {            

            public void onClick(View v) {
                mViewPager.setCurrentItem(1);

            }
        });
    }

    /**
     * Adapter for ViewPAger that manages background interactions with fragments
     */
    private class MyAdapter extends FragmentPagerAdapter{

        private Context mContext;
        private String[] frags = {Headlines.class.getName(), Kerala.class.getName()};

        public MyAdapter(FragmentActivity activity) {
            super(activity.getSupportFragmentManager());
            mContext = activity;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            Fragment frag = (Fragment) super.instantiateItem(container, position);
            if(frag instanceof MessageLoader){
                mLoader = (MessageLoader) frag;
            }
            return frag;
        }

        @Override
        public Fragment getItem(int pos) {
            return Fragment.instantiate(mContext, frags[pos]);
        }

        @Override
        public int getCount() {
            return frags.length;
        }

    }




}

6 个答案:

答案 0 :(得分:5)

function1()的签名更改为:

public static void function1(Fragment f)

并使用:

button = (Buton) f.getActivity().findViewById(R.id.button1);

而不是:

button = (Buton) getActivity().findViewById(R.id.button1);

并调用这样的方法:

function1(this);

但是,如果没有任何目的,这个方法应该是实例方法而不是静态方法。

答案 1 :(得分:2)

不要使用静态方法,因为它不能引用Fragment1实例,除非您将其作为输入参数提供。除了改变按钮的发现如下:

button = (Buton) getView().findViewById(R.id.button1);

答案 2 :(得分:0)

您目前有:

static Button button;

您应该删除static关键字,而是写:

private Button button;

答案 3 :(得分:0)

这里没有任何理由可以保持静态(除了你在CAPITALS中放入的常量应该同时声明为static final)。

从代码中删除所有static个关键字,它应该有效(除了CAPITALIZED变量):

private Button button;

// ...

public void function1() {
  // ...
}

答案 4 :(得分:0)

@覆盖 public View onCreateView(LayoutInflater inflater,ViewGroup容器,         Bundle savedInstanceState){

View v = inflater.inflate(R.layout.first_fragment, container, false);
button=(Button) v.findViewById(R.id.button1);


return v;

}

答案 5 :(得分:0)

您必须使用该布局来扩充该特定布局以查找ID。

**

View v = inflater.inflate(R.layout.first_fragment, container, false);
button=(Button) v.findViewById(R.id.button1);
return v;

**