android中按一个按钮弹出字,允许用户在Android中长按一次即可编辑按钮文字
我想允許App用戶在Android中更改Button文本。 當(dāng)用戶單擊按鈕時(shí),它應(yīng)該執(zhí)行某些操作,但是當(dāng)他/她長按按鈕時(shí),將彈出一個(gè)編輯文本,并且無論用戶鍵入什么內(nèi)容都應(yīng)另存為按鈕文本。
到目前為止,我已經(jīng)完成了以下操作。
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;
}
}
在google上您會(huì)找到答案,請(qǐng)?jiān)诎l(fā)布問題之前先進(jìn)行研究。 您會(huì)發(fā)現(xiàn)一些帖子回答您的問題。
您面臨什么問題?
嘗試這樣:
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:
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content">
android:id="@+id/edit_dialog"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
然后
嗨,Cgx。 嘗試了您的解決方案,但在longClick上沒有任何反應(yīng)
什么! 我有測(cè)試前期但工作正常
如果解決了,請(qǐng)回答,謝謝!,:)
還有一件事。 當(dāng)我保存文本時(shí),它是一個(gè)臨時(shí)更改。 我想永久保存它,直到通過LongClick再次更改它為止。 如何做到這一點(diǎn)?
您可以創(chuàng)建一個(gè)輸入對(duì)話框以從用戶獲取文本
btn1.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
builder.show();
return true;
}
});
}
并設(shè)置btn1的文本,如下所示:
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
btn1.setText(input.getText().toString());
}
});
總結(jié)
以上是生活随笔為你收集整理的android中按一个按钮弹出字,允许用户在Android中长按一次即可编辑按钮文字的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: android 自定义弹窗diss,An
- 下一篇: android 使用c 代码实现,JNI