来自另一个活动android的按钮上的setText

时间:2015-11-08 18:13:33

标签: java android android-intent settext

我遇到了问题,我想点击列表,调用新活动并将按钮重命名为其他名称。

我尝试了几件事,没有任何效果,有人可以帮助我吗?

我的班级EditarTimes

private AdapterView.OnItemClickListener selecionarTime = new AdapterView.OnItemClickListener() {

    public void onItemClick(AdapterView arg0, View arg1, int pos, long id) {
        t = times.get(pos);

        CadastroTimes cad = new CadastroTimes();
        CadastroTimes.salvar.setText("Alterar");
        Intent intent = new Intent(EditarTimes.this, CadastroTimes.class);
        startActivity(intent);


    }

};
public class CadastroTimes extends AppCompatActivity {

    private Time t;
    private timeDatabase db;
    private EditText edID;
    private EditText edNome;
    public Button salvar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cadastro_times);

        edID = (EditText) findViewById(R.id.edID);
        edNome = (EditText) findViewById(R.id.edNome);
        db = new timeDatabase(getApplicationContext());
        salvar = (Button) findViewById(R.id.btnCadastrar);
        salvar.setText("Cadastrar");
        String newString;
        if (savedInstanceState == null) {
            Bundle extras = getIntent().getExtras();
            if(extras == null) {
                newString= null;
            } else {
                newString= extras.getString("Alterar");
            }
        } else {
            newString= (String) savedInstanceState.getSerializable("Alterar");
        }

        //button in CadastroTimes activity to have that String as text
        System.out.println(newString + " AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
        salvar.setText(newString);
    }

    public void salvarTime(View v) {
        t = new Time();
        t.setNome(edNome.getText().toString());

        if (salvar.getText().equals("Alterar")) {
            db.atualizar(t);
            exibirMensagem("Time atualizado com sucesso!");
        } else {
            db.salvar(t);
            exibirMensagem("Time cadastrado com sucesso!");
        }

        Intent intent = new Intent(this, EditarTimes.class);
        startActivity(intent);

    }


    private void limparDados() {
        edID.setText("");
        edNome.setText("");
        edNome.requestFocus();
    }

    private void exibirMensagem(String msg) {
        Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
    }

}
public class EditarTimes extends AppCompatActivity {

    private Time t;
    private List times;
    private timeDatabase db;
    private ListView lvTimes;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_editar_times);

        lvTimes = (ListView) findViewById(R.id.lvTimes);
        lvTimes.setOnItemClickListener(selecionarTime);
        lvTimes.setOnItemLongClickListener(excluirTime);
        times = new ArrayList();
        db = new timeDatabase(getApplicationContext());
        atualizarLista();
    }

    private void excluirTime(final int idTime) {


        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Excluir time?")
                .setIcon(android.R.drawable.ic_dialog_alert)
                .setMessage("Deseja excluir esse time?")
                .setCancelable(false)
                .setPositiveButton(getString(R.string.sim),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                if (db.deletar(idTime)) {
                                    atualizarLista();
                                    exibirMensagem(getString(R.string.msgExclusao));
                                } else {
                                    exibirMensagem(getString(R.string.msgFalhaExclusao));
                                }

                            }
                        })
                .setNegativeButton(getString(R.string.nao),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                dialog.cancel();
                            }
                        });
        builder.create();
        builder.show();

        atualizarLista();

    }

    private void atualizarLista() {

        times = db.listAll();
        if (times != null) {
            if (times.size() > 0) {
                TimeListAdapter tla = new TimeListAdapter(
                        getApplicationContext(), times);
                lvTimes.setAdapter(tla);
            }

        }

    }

    private AdapterView.OnItemClickListener selecionarTime = new AdapterView.OnItemClickListener() {

        public void onItemClick(AdapterView arg0, View arg1, int pos, long id) {
            t = times.get(pos);

            Intent intent = new Intent(EditarTimes.this, CadastroTimes.class);
            String strName = "Alterar";
            intent.putExtra("Alterar", strName);
            startActivity(intent);




            //preecherDados(t);

        }

    };

    private AdapterView.OnItemLongClickListener excluirTime = new AdapterView.OnItemLongClickListener() {

        public boolean onItemLongClick(AdapterView arg0, View arg1,
                                       int pos, long arg3) {
            excluirTime(times.get(pos).getId());
            return true;
        }


    };

    /*private void preecherDados(Time time) {
        edID.setText(String.valueOf(time.getId()));
        edNome.setText(time.getNome());
    }*/

    private void exibirMensagem(String msg) {
        Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
    }

    public void telaCadastrar(View view) {
        Intent intent = new Intent(this, CadastroTimes.class);
        startActivity(intent);
    }

    public void botaoSair(View view) {
        Intent intent = new Intent(this, TelaInicial.class);
        startActivity(intent);
    }
}

10 个答案:

答案 0 :(得分:9)

您可以将按钮标题传递给CadastroTimes,意图为

Intent intent = new Intent(EditarTimes.this, CadastroTimes.class);
intent.putExtra("buttontxt","Changed Text");
startActivity(intent);

然后在CadastroTimes.java中将按钮的文本设置为您传递的新值。代码如下:

button = (Button)findViewById(R.id.button); // This is your reference from the xml. button is my name, you might have your own id given already.
Bundle extras = getIntent().getExtras();
String value = ""; // You can do it in better and cleaner way
if (extras != null) {
    value = extras.getString("buttontxt");
}
button.setText(value);

请务必在onCreate

之后setContentView内进行此操作

答案 1 :(得分:3)

//From Activity
Intent intent = new Intent(EditarTimes.this, CadastroTimes.class);
intent.pueExtra("change_tag", "text to change");
startActivity(intent)

//To Activity

public void onCreate(..){

    Button changeButton = (Button)findViewById(R.id.your_button);
    // Button to set received text
    Intent intent = getIntent();

    if(null != intent && 
             !TextUtils.isEmpty(intent.getStringExtra("change_tag"))) {


        String changeText = intent.getStringExtra("change_tag");
        // Extracting sent text from intent

        changeButton.setText(changeText);
        // Setting received text on Button

     }
}

对不起,我有点迟了。但是,我希望能帮到你。

答案 2 :(得分:1)

1:使用intent.putExtra()从一个活动另一个活动共享一个值,如:

ActivityOne.class

Intent intent = new Intent(getApplicationContext(), ActivityTwo.class);
intent.putExtra("key", "value");
intent.startActivity();

ActivityTwo.class

Intent intent = getIntent();
String var = intent.getStringExtra("key");

2:以编程方式修改按钮文本:

btn_object.setText(var);

希望这会对你有所帮助

答案 3 :(得分:0)

好的,所以第一步是选择你想要的按钮并将其作为公共静态对象(并将其放在类的顶部)。

public static Button button;

然后你可以在另一个类中使用它来操纵它:

 ClassName.button.setText("My Button");

在你的情况下,它是

CadastroTimes.salvar.setText("Alterar");

答案 4 :(得分:0)

现在,我找到了你:

EditarTimes listview活动//set setOnItemClickListener youtListView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view,int position, long id) { Intent i = new Intent(EditarTimes.this, CadastroTimes.class); //text which you want to display on the button to CadastroTimes activity String strName = "hello button"; i.putExtra("STRING_I_NEED", strName); } });

CadastroTimes

onCreate()活动中,

String newString; if (savedInstanceState == null) { Bundle extras = getIntent().getExtras(); if(extras == null) { newString= null; } else { newString= extras.getString("STRING_I_NEED"); } } else { newString= (String) savedInstanceState.getSerializable("STRING_I_NEED"); } 方法下,获取文本字符串: -

{{_id}}
CadastroTimes活动中的

//按钮将该String作为文本     yourButton.setText(newString);

答案 5 :(得分:0)

更改按钮文字:

  1. 使用静态方法从其他活动调用以直接修改按钮标题。
  2. 使用意图功能,这是首选。
  3. 使用界面并实现它,用于以激烈和遗忘的方式在活动或片段之间进行通信。

答案 6 :(得分:0)

如果您要从中更改值,请不要通过意图进行操作,您可以使用文件将值保存到文件中,或者您具有多个值,请使用数据库和访问权限 值oncreate设置文本的值。...

答案 7 :(得分:0)

在我的情况下,我必须从样式为EditText的{​​{1}}发送一个Dialog值,然后从Activity中检索该值。 与上面的某些答案类似,也是可行的。

TimerActivity.class

Service


然后在Service类中检索值,并在public void buttonClick_timerOK(View view) { // Identify the (EditText) for reference: EditText editText_timerValue; editText_timerValue = (EditText) findViewById(R.id.et_timerValue); // Required 'if' statement (to avoid NullPointerException): if (editText_timerValue != null) { // Continue with Button code.. // Convert value of the (EditText) to a (String) String string_timerValue; string_timerValue = editText_timerValue.getText().toString(); // Declare Intent for starting the Service Intent intent = new Intent(this, TimerService.class); // Add Intent-Extras as data from (EditText) intent.putExtra("TIMER_VALUE", string_timerValue); // Start Service startService(intent); // Close current Activity finish(); } else { Toast.makeText(TimerActivity.this, "Please enter a Value!", Toast.LENGTH_LONG).show(); } } 中使用它。

TimerService.class

onStartCommand


希望我的贡献能有所帮助!
祝您编程愉快!

答案 8 :(得分:0)

访问另一个活动的视图引用是一种不道德的行为。因为无法保证在您访问参考文献时参考文献仍然存在(考虑null参考风险)。

您需要做的是使其他Activity从数据源(例如,持久性存储或共享首选项)读取值(要显示),而另一个Activity处理这些值。因此,看起来好像它在更改另一个活动的值,但实际上它是从数据源获取值。

答案 9 :(得分:0)

使用 SharedPreferences:

注意:SharedPreferences 会在您关闭应用后保存数据,但删除后会丢失。

在 EditarTimes.java 中:

private AdapterView.OnItemClickListener selecionarTime = new AdapterView.OnItemClickListener() {

    public void onItemClick(AdapterView arg0, View arg1, int pos, long id) {
        t = times.get(pos);

        SharedPreferences.Editor editor = getSharedPreferences("DATA", MODE_PRIVATE).edit();
        editor.putString("btnText", "Your desired text");
        editor.apply();
        Intent intent = new Intent(EditarTimes.this, CadastroTimes.class);
        startActivity(intent);

    }

};

在 CadastroTimes.java 中

public Button salvar;

salvar.setText(getSharedPreferences("DATA", MODE_PRIVATE).getString("btnText", ""));
//note that default value should be blank