蜂窝前(Android 3),每个活动均已注册,以通过布局XML中的onClick
标记处理按钮单击:
android:onClick="myClickMethod"
在该方法中,您可以使用view.getId()
和switch语句来执行按钮逻辑。
随着Honeycomb的引入,我将这些活动分解为片段,可以在许多不同的活动中重用这些片段。 按钮的大多数行为都是独立于活动的,我希望代码驻留在Fragments文件中, 而无需使用为每个按钮注册OnClickListener
的旧方法(1.6版之前)。
final Button button = (Button) findViewById(R.id.button_id);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
}
});
问题是当我的布局膨胀时,仍然是托管活动正在接收按钮点击,而不是单个片段。 是否有一个好的方法
- 注册片段以接收按钮点击?
- 将点击事件从“活动”传递到它们所属的片段?
#1楼
在处理片段时,我宁愿使用代码中的单击处理,也不愿使用XML中的onClick
属性。
将您的活动迁移到片段时,这变得更加容易。 您可以直接从每个case
块调用click处理程序(以前在XML中设置为android:onClick
)。
findViewById(R.id.button_login).setOnClickListener(clickListener);
...
OnClickListener clickListener = new OnClickListener() {
@Override
public void onClick(final View v) {
switch(v.getId()) {
case R.id.button_login:
// Which is supposed to be called automatically in your
// activity, which has now changed to a fragment.
onLoginClick(v);
break;
case R.id.button_logout:
...
}
}
}
在处理片段中的点击时,对我来说,这比android:onClick
更简单。
#2楼
我更喜欢使用以下解决方案来处理onClick事件。 这也适用于活动和片段。
public class StartFragment extends Fragment implements OnClickListener{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_start, container, false);
Button b = (Button) v.findViewById(R.id.StartButton);
b.setOnClickListener(this);
return v;
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.StartButton:
...
break;
}
}
}
#3楼
这是另一种方式:
1,创建一个BaseFragment像这样:
public abstract class BaseFragment extends Fragment implements OnClickListener
2.使用
public class FragmentA extends BaseFragment
代替
public class FragmentA extends Fragment
3,活动中
public class MainActivity extends ActionBarActivity implements OnClickListener
和
BaseFragment fragment = new FragmentA;
public void onClick(View v){
fragment.onClick(v);
}
希望能帮助到你。
#4楼
除了Blundell的答案,
如果您有更多片段,并且拥有大量的onClicks:
活动:
Fragment someFragment1 = (Fragment)getFragmentManager().findFragmentByTag("someFragment1 ");
Fragment someFragment2 = (Fragment)getFragmentManager().findFragmentByTag("someFragment2 ");
Fragment someFragment3 = (Fragment)getFragmentManager().findFragmentByTag("someFragment3 ");
...onCreate etc instantiating your fragments
public void myClickMethod(View v){
if (someFragment1.isVisible()) {
someFragment1.myClickMethod(v);
}else if(someFragment2.isVisible()){
someFragment2.myClickMethod(v);
}else if(someFragment3.isVisible()){
someFragment3.myClickMethod(v);
}
}
在您的片段中:
public void myClickMethod(View v){
switch(v.getid()){
// Just like you were doing
}
}
#5楼
Butterknife可能是解决混乱问题的最佳解决方案。 它使用注释处理器生成所谓的“旧方法”样板代码。
但是onClick方法仍然可以与自定义充气机一起使用。
如何使用
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup cnt, Bundle state) {
inflater = FragmentInflatorFactory.inflatorFor(inflater, this);
return inflater.inflate(R.layout.fragment_main, cnt, false);
}
实作
public class FragmentInflatorFactory implements LayoutInflater.Factory {
private static final int[] sWantedAttrs = { android.R.attr.onClick };
private static final Method sOnCreateViewMethod;
static {
// We could duplicate its functionallity.. or just ignore its a protected method.
try {
Method method = LayoutInflater.class.getDeclaredMethod(
"onCreateView", String.class, AttributeSet.class);
method.setAccessible(true);
sOnCreateViewMethod = method;
} catch (NoSuchMethodException e) {
// Public API: Should not happen.
throw new RuntimeException(e);
}
}
private final LayoutInflater mInflator;
private final Object mFragment;
public FragmentInflatorFactory(LayoutInflater delegate, Object fragment) {
if (delegate == null || fragment == null) {
throw new NullPointerException();
}
mInflator = delegate;
mFragment = fragment;
}
public static LayoutInflater inflatorFor(LayoutInflater original, Object fragment) {
LayoutInflater inflator = original.cloneInContext(original.getContext());
FragmentInflatorFactory factory = new FragmentInflatorFactory(inflator, fragment);
inflator.setFactory(factory);
return inflator;
}
@Override
public View onCreateView(String name, Context context, AttributeSet attrs) {
if ("fragment".equals(name)) {
// Let the Activity ("private factory") handle it
return null;
}
View view = null;
if (name.indexOf('.') == -1) {
try {
view = (View) sOnCreateViewMethod.invoke(mInflator, name, attrs);
} catch (IllegalAccessException e) {
throw new AssertionError(e);
} catch (InvocationTargetException e) {
if (e.getCause() instanceof ClassNotFoundException) {
return null;
}
throw new RuntimeException(e);
}
} else {
try {
view = mInflator.createView(name, null, attrs);
} catch (ClassNotFoundException e) {
return null;
}
}
TypedArray a = context.obtainStyledAttributes(attrs, sWantedAttrs);
String methodName = a.getString(0);
a.recycle();
if (methodName != null) {
view.setOnClickListener(new FragmentClickListener(mFragment, methodName));
}
return view;
}
private static class FragmentClickListener implements OnClickListener {
private final Object mFragment;
private final String mMethodName;
private Method mMethod;
public FragmentClickListener(Object fragment, String methodName) {
mFragment = fragment;
mMethodName = methodName;
}
@Override
public void onClick(View v) {
if (mMethod == null) {
Class<?> clazz = mFragment.getClass();
try {
mMethod = clazz.getMethod(mMethodName, View.class);
} catch (NoSuchMethodException e) {
throw new IllegalStateException(
"Cannot find public method " + mMethodName + "(View) on "
+ clazz + " for onClick");
}
}
try {
mMethod.invoke(mFragment, v);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new AssertionError(e);
}
}
}
}
来源:oschina
链接:https://my.oschina.net/u/3797416/blog/3162132