【问题标题】:Create layout code that can be shared between many activities创建可以在许多活动之间共享的布局代码
【发布时间】:2015-12-16 08:29:13
【问题描述】:
这是用于确认的弹出窗口的屏幕截图。我在很多方面都使用这种类型的弹出窗口,所以创建了关闭按钮X。我在所有弹出窗口的布局中都包含了关闭按钮 xml,但我希望它可以重复使用(共享)。
我不知道如何在 android 中以编程方式创建按钮,因此我可以保存到一个通用文件并与所有活动一起使用。例如,我可以创建 closeButton.java,然后在任何布局中包含关闭按钮,并在其上添加一个常见的单击侦听器。
【问题讨论】:
标签:
android
android-layout
popover
code-reuse
【解决方案1】:
Android Views,即使是 xml 文件中提到的那些,也只是 Java 类。你可以创建一个CloseButton.java 类extends Button,把逻辑放在那里,然后在你所有的xml布局中使用这个类,就像任何其他View一样:
<com.example.project.by.nicky.CloseButton
android:id="@+id/someId"
android:layout_width=""
android:layout_height="" />
【解决方案2】:
解决此问题的一种方法是创建一个扩展 android 按钮或图像的服装视图,这将是您的 X 按钮。
比起从你的构造函数来看,只需注册点击事件。
class XButton extends ImageView{
public XButton(Context context) {
super(context);
init();
}
public XButton(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public XButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init(){
setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// do some thing
}
});
}
}
【解决方案3】:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// use MyPopUpWindow as below no need to create layout in each activity
MyPopUpWindow popup = new MyPopUpWindow(this);
popup.setContentView(your_layout);
popup.setConfirmationListener(new ConfirmationListener() {
@Override
public void onConfirm() {
// TODO Auto-generated method stub
}
});
}
}
MyPopUpWindow 类
import android.content.Context;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.PopupWindow;
public class MyPopUpWindow extends PopupWindow {
private Button mCrossBtn;
private Button mConfirmationBtn;
private ConfirmationListener mConfirmationListener;
public MyPopUpWindow(Context ctx){
super(ctx);
}
@Override
public void setContentView(View contentView) {
super.setContentView(contentView);
mCrossBtn = contentView.findViewById(R.id.cross_button_id);
mCrossBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
MyPopUpWindow.this.dismiss();
}
});
mConfirmationBtn = contentView.findViewById(R.id.confirm_button_id);
mConfirmationBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
if(mConfirmationListener != null){
mConfirmationListener.onConfirm();
}
}
});
}
interface ConfirmationListener{
public void onConfirm();
}
public void setConfirmationListener(ConfirmationListener l) {
mConfirmationListener = l;
}
}