Ped*_*rom 3 android android-fragments android-activity
我是Android开发的新手,我正在尝试处理从片段类到我的活动的多次按钮点击.通过在我的fragment类中创建一个监听器,然后让activity类实现该接口,我能够弄清楚如何处理一次单击.
myFragment.java
onResetGridListener mCallback;
// Container activity must implement this interface
public interface onResetGridListener
{
public void ResetGridClicked();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.tilemap, container, false);
Button button = (Button) view.findViewById(R.id.resetGrid_button);
// A simple OnClickListener for our button. You can see here how a Fragment can encapsulate
// logic and views to build out re-usable Activity components.
button.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
mCallback.ResetGridClicked();
}
});
return view;
}
Run Code Online (Sandbox Code Playgroud)
这很完美,但是现在我在同一个片段中有另一个按钮,还有更多的按钮,所以我想知道如何处理这个.活动可以实现多个接口(每个按钮一个),还是我错误的方式?
感谢您的时间和信息
您可以让Fragment实现接口.然后它看起来像这样:
//init buttons somewhere
button.setOnClickListener(this);
anotherButton.setOnClickListener(this);
//that's a Fragment method
public void onClick(View v)
{
switch(v.getId()){
case R.id.button1:
doStuff();
break;
case R.id.button2:
doStuff();
break;
}
}
Run Code Online (Sandbox Code Playgroud)