我在 XML 中定义了一个 Layout
,它由几个 Button
组成。
目前我正在 OnCreate
方法中执行此操作,以针对按钮定义事件处理程序:
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button newPicButton = (Button)findViewById(R.id.new_button);
newPicButton.setOnClickListener(btnListener);
..... similarly for other buttons too
.....
}
在 Button
的 onClick
事件中,我启动相机 Intent
以获取图片并在 onActivityResult
回调我再次设置事件处理程序以及像这样设置 View
:
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
setContentView(R.layout.main);
Button newPicButton = (Button)findViewById(R.id.new_button);
newPicButton.setOnClickListener(btnListener);
...similarly for other buttons too
}
我是 android 新手,这种每次都重新定义事件的方法对我来说似乎很脏。我想知道在这样的场景中定义按钮事件处理程序的最佳实践是什么。
编辑:粘贴我的完整类(class)
public class CameraAppActivity extends Activity
{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button newPicButton = (Button)findViewById(R.id.new_button);
newPicButton.setOnClickListener(btnListener);
}
//---create an anonymous class to act as a button click listener---
private OnClickListener btnListener = new OnClickListener()
{
public void onClick(View v)
{
//Intent newPicIntent = new Intent(v.getContext(), NewPictureActivity.class);
//startActivityForResult(newPicIntent, 0);
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, 999);
}
};
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
setContentView(R.layout.main);
Button newPicButton = (Button)findViewById(R.id.new_button);
newPicButton.setOnClickListener(btnListener);
//if I comment last two lines nothing happens when I click on button
}
主要问题是
setContentView(R.layout.main);
Button newPicButton = (Button)findViewById(R.id.new_button);
newPicButton.setOnClickListener(btnListener);
在 onActivityResult
中重新注册事件.. 是正确的方法吗?还是我做错了什么?因为如果我不重新注册事件,当我点击按钮时不会发生任何事情。
最佳答案
为什么不在 XML 布局中注册 onClick 事件,然后在代码中处理。我会这样做:
<Button
android:id="@+id/my_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click me"
android:onClick="onBtnClicked">
</Button>
现在创建一个处理点击的方法
public void onBtnClicked(View v){
if(v.getId() == R.id.my_btn){
//handle the click here
}
}
或者,您可以为代码中的每个项目单独设置 OnClickListener。然后使用 if/else 或 switch 语句来确定来源。
这样您就可以使用一种方法来处理一个布局中的所有按钮。
更新:
虽然这是一种有效的方法,但我强烈推荐第二种选择。它更干净,更容易维护,尤其是在处理 fragment 时。
关于android - 在android中定义按钮事件的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6372104/