从另一个活动设置按钮上的文本 Android

18

我有一个问题,我想点击列表,调用一个新的活动并将按钮重命名为另一个名称。

我尝试了几个方法,但没有成功,有人能帮忙吗?

我的类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<Time> 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<Time>();
        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);
        }

    };

    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 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);
    }
}

如果按钮在“CadastroTimes”中,则执行“CadastroTimes”,而不是在“EditarTimes”中执行。 - ρяσѕρєя K
按钮在CadastroTimes.class中,一切都正常,我只需要点击列表项,调用活动CadastroTimes并更改按钮名称。 - Alan Santos
11个回答

13
你可以使用意图将按钮标题传递给 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);

记得在setContentView之后,在onCreate中执行此操作。


按钮是空白的,没有任何文字:{ 我想我不知道该怎么做 :{ - Alan Santos
我已经添加了可以复制粘贴的代码。请将更改后的代码放入适当的类中。您需要在CadastroTimes.java中更改按钮ID(请使用您自己的按钮ID而不是我的R.id.button)。有可能您的getExtras为空。因此,如果您按照我给出的方式更改EditarTimes中的代码,则应该可以正常工作。让我知道。 - Swagata Acharyya
我放弃了,我尝试了很多次但是无法让它工作,我正在创建一个新的活动来解决我的问题,谢谢你的帮助,对于浪费你的时间我感到抱歉。 - Alan Santos

4
//From Activity
Intent intent = new Intent(EditarTimes.this, CadastroTimes.class);
intent.putExtra("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:使用 intent.putExtra() 将一个值从一个活动共享到另一个活动,如下所示:

ActivityOne.class 中:

startActivity(
    Intent(
        applicationContext, 
        ActivityTwo::class.java
    ).putExtra(
        "key", 
        "value"
    )
)

ActivityTwo.class中:
var value = ""
if (intent.hasExtra("key")
    value = intent.getStringExtra("key")

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

btn_object.text = value

希望这能对您有所帮助


0
好的,那么第一步就是将你想要的按钮设置为公共静态对象(并将其放在类的顶部)。
public static Button button;

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

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

在你的情况下,它是

CadastroTimes.salvar.setText("Alterar");

公共类CadastroTimes扩展自AppCompatActivity {private Time t; private timeDatabase db; private EditText edID; private EditText edNome; public static Button salvar;} - Alan Santos
是的,那样就可以在不同的类中使用了。如果这样对你可行,请告诉我。 - alex23434
我无法在编辑团队类中使用salvar.setText("Alterar");。 - Alan Santos
{btsdaf} - RestingRobot

0

现在,我得到了你:

你的带有listviewEditarTimes活动:

//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");
}

//在CadastroTimes活动中的按钮将该字符串作为文本 yourButton.setText(newString);


这似乎不可能,尝试检查 CadastroTimes 活动中是否接收到了字符串值,然后可以将其用作按钮文本。请尽快告诉我。 - Androider
String strName = null; 请根据我更新的答案,更新它的值。 - Androider
如果我点击列表,我需要字符串“Alterar”,如果我使用按钮打开屏幕CadastroTimes,我需要字符串“Cadastrar”。 - Alan Santos
无论如何,在onitemclickListener中,您将strName从第一个活动发送为空值到另一个活动,因此您会得到按钮文本的空值。那就是之前的主要问题。谢谢。请相应地更新您的代码。 - Androider
如果我点击列表,字符串是“Alterar”,如果我点击按钮,字符串是“null”lol。 - Alan Santos
显示剩余7条评论

0
就我所思,我认为问题不在于您提供的代码,因为它似乎已经正确实现了。可能是因为您在实际代码中保存了activityState,但由于其未被正确实现,因此在onCreate方法中找到的savedInstanceState不为空,但所需信息缺失或不正确。这就是为什么newString为空,salvar textview为空白的原因。
在这里,我需要知道哪一个对您更有用——来自getIntent()还是savedInstanceState的信息?您提供的代码让我假设savedInstanceState更受欢迎。
如果您喜欢savedInstanceState,那么您可以像这样使用SharedPreferences来获取所需的值:

     private SharedPreferences mPrefs;
     private String newString;

     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);

         ........

         // try to get the value of alterarValue from preference

         mPrefs = getSharedPreferences("MyData", MODE_PRIVATE);
         newString = mPrefs.getString("alterarValue", "");
         if (newString.equals("")){

             // we have not received the value
             // move forward to get it from bundle

          newString = getIntent().getStringExtra("Alterar");    
         }

         // now show it in salvar
        salvar.setText(newString);  
     }

     protected void onPause() {
         super.onPause();

         // you may save activity state or other info in this way

         SharedPreferences.Editor ed = mPrefs.edit();
         ed.putString("alterarValue", newString);
         ed.commit();
     }

或者如果您不需要从savedInstanceState中获取它,请使用它:


protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);

         ........

         // try to get the value of alterarValue from bundle

         String newString = getIntent().getStringExtra("Alterar");  

         // now show it in salvar
        salvar.setText(newString);  
     }

这就是我所知道的全部。希望能有所帮助。如果出现任何问题,请告诉我。


0

访问另一个Activity的视图引用是一种不良实践。因为在您访问它时,无法保证引用是否仍然存在(考虑null引用风险)。

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


0
如果你想改变值,而不是通过意图进入活动,你可以使用文件将值保存到文件中,或者如果你有多个值,可以使用数据库并在onCreate中访问该值来设置文本的值...

0

更改按钮文本的方法:

  1. 使用静态方法从其他活动中调用,直接修改按钮标题。
  2. 使用意图功能,这是首选方法。
  3. 使用接口并实现它,用于在活动或片段之间以“点火和忘记”原则进行通信。

0
在我的情况下,我需要从一个对话框样式的活动中发送一个EditText值,然后从一个Service中检索它。 我的示例与上面的一些答案类似,这些答案也是可行的。

TimerActivity.class
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();
    }
}


然后在我的Service类中,我检索了这个值,并在onStartCommand中使用它。

TimerService.class

// Retrieve the user-data from (EditText) in TimerActivity
    intent.getStringExtra("TIMER_VALUE");   //  IS THIS NEEDED, SINCE ITS ASSIGNED TO A STRING BELOW TOO?

    // Assign a String value to the (EditText) value you retrieved..
    String timerValue;
    timerValue = intent.getStringExtra("TIMER_VALUE");

    // You can also convert the String to an int, if needed.

    // Now you can reference "timerValue" for the value anywhere in the class you choose.


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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接