为什么onClickListener无法在我的ViewPager Frament中运行

时间:2017-07-20 15:01:54

标签: android android-layout android-fragments

所以基本上我有一个viewpager,它的片段是动态添加和删除的。我想要做的是在片段中设置onClick函数并执行与该片段相关的操作。 以下是我的代码。

MainFragment.java

public class MainFragment extends Fragment implements View.OnClickListener {
private static final String ARG_LAYOUT="layout";
private QuoteData quoteData;
private String textTospeak;
private Speaker speaker;
//Returns an Instance of fragment
static Fragment newInstance(int layoutId, QuoteData quoteData) {
    Fragment result=new MainFragment();
    //quoteData = quoteDat;
    Bundle args=new Bundle();
    args.putInt(ARG_LAYOUT, layoutId);
    args.putString("quote", quoteData.getQuote());
    args.putString("author", quoteData.getAuthorName());
    args.putString("imgurl", quoteData.getAuthorName());
    result.setArguments(args);
    return(result);
}

public MainFragment(){}



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

    View fragmentView = inflater.inflate(getArguments().getInt(ARG_LAYOUT),container, false);
    TextView textview = (TextView)fragmentView.findViewById(R.id.quotetext);
    String text = (String)getArguments().get("quote") +"\n\t\t\t"+getArguments().get("author");
    textview.setText(text);

    ImageView imageView = (ImageView) fragmentView.findViewById(R.id.speak);
    imageButton.setOnClickListener(this);
    return(fragmentView);

}

@Override
public void onClick(View v) {
    //speak();
    Toast.makeText(v.getContext(),"Show me something", Toast.LENGTH_SHORT);
}

}

然后我在Fragment的xml中使用了OnClick属性,并在我的MainActivity中创建了一个函数,该函数也不起作用。

我错过了什么?

1 个答案:

答案 0 :(得分:0)

替换:

@Override
public void onClick(View v) {
    //speak();
    Toast.makeText(v.getContext(),"Show me something", Toast.LENGTH_SHORT);
}

使用:

    @Override
        public void onClick(View v) {
            //speak();
           if(v.getId() == imageButton.getId()){
            Toast.makeText(v.getContext(),"Show me something", Toast.LENGTH_SHORT).show();
          }
        }