我想允许App用户更改Android中的Button文本。当用户单击按钮时,它应该执行某些操作,但是当他/她长按按钮时,应该弹出一个edittext&任何用户类型都应保存为按钮文本。 到目前为止,我已经完成了以下事情。
btn1 = (Button) findViewById(R.id.button1);
etLabel = (EditText) findViewById(R.id.etName);
btn1.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
// How to pop-up edittext from here
// to allow user change Button name
btn1.setText(name);
return true;
}
});
}
public void onButtonClick(View view) {
switch (view.getId()) {
case R.id.button1:
// do something else here
break;
}
}
答案 0 :(得分:0)
您可以create a input dialog从用户那里获取文字
btn1.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
builder.show();
return true;
}
});
}
并设置btn1的文本,如下所示:
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
btn1.setText(input.getText().toString());
}
});
答案 1 :(得分:0)
尝试这样:
public class SOdemoAcitvity extends AppCompatActivity {
private Button btn;
private EditText edit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.so_demo);
btn = (Button) findViewById(R.id.btn_demo);
edit = (EditText) findViewById(R.id.edit_text);
btn.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
showDialog(edit.getText().toString());
return true;
}
});
}
private void showDialog(String str) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("input text");
View view = LayoutInflater.from(this).inflate(R.layout.dialog_view, null);
final EditText edit_dialog = (EditText) view.findViewById(R.id.edit_dialog);
edit_dialog.setText(str);
builder.setView(view);
builder.setNegativeButton("cancel",null);
builder.setPositiveButton("confirm", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
btn.setText(edit_dialog.getText().toString());
}
});
builder.show();
}
}
dialog_view xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="@+id/edit_dialog"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
然后