【问题标题】:setText on button from another activity android来自另一个活动android的按钮上的setText
【发布时间】:2016-02-09 09:37:28
【问题描述】:

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

我尝试了几件事,但没有成功,有人可以帮助我吗?

我的班级EditarTimes

私有 AdapterView.OnItemClickListener 选择时间 = new AdapterView.OnItemClickListener() {

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

        地籍时间 cad = new CadastroTimes();
        CadastroTimes.salvar.setText("Alterar");
        Intent intent = new Intent(EditarTimes.this, CadastroTimes.class);
        开始活动(意图);


    }

};
公共类 CadastroTimes 扩展 AppCompatActivity {

    私人时间 t;
    私人时间数据库;
    私人 EditText edID;
    私人 EditText edNome;
    公共按钮萨尔瓦;

    @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());
        萨尔瓦=(按钮)findViewById(R.id.btnCadastrar);
        salvar.setText("地籍");
        字符串新字符串;
        if (savedInstanceState == null) {
            捆绑附加服务 = getIntent().getExtras();
            如果(额外==空){
                新字符串=空;
            } 别的 {
                newString= extras.getString("Alterar");
            }
        } 别的 {
            newString= (String) savedInstanceState.getSerializable("Alterar");
        }

        //CadastroTimes 活动中的按钮以将该字符串作为文本
        System.out.println(newString + " AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
        salvar.setText(newString);
    }

    公共无效salvarTime(查看v){
        t = 新时间();
        t.setNome(edNome.getText().toString());

        if (salvar.getText().equals("Alterar")) {
            db.atualizar(t);
            exibirMensagem("时间 atualizado com sucesso!");
        } 别的 {
            db.salvar(t);
            exibirMensagem("时间地籍 com sucesso!");
        }

        Intent intent = new Intent(this, EditarTimes.class);
        开始活动(意图);

    }


    私人无效limparDados(){
        edID.setText("");
        edNome.setText("");
        edNome.requestFocus();
    }

    私人无效exibirMensagem(字符串味精){
        Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
    }

}
公共类 EditarTimes 扩展 AppCompatActivity {

    私人时间 t;
    私人名单时间;
    私人时间数据库;
    私有 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(selecinarTime);
        lvTimes.setOnItemLongClickListener(excluirTime);
        次 = 新的 ArrayList();
        db = new timeDatabase(getApplicationContext());
        atualizarLista();
    }

    私人无效excluirTime(最终int idTime){


        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("排除时间?")
                .setIcon(android.R.drawable.ic_dialog_alert)
                .setMessage("Deseja 排除时间?")
                .setCancelable(假)
                .setPositiveButton(getString(R.string.sim),
                        新的 DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                如果(db.deletar(idTime)){
                                    atualizarLista();
                                    exibirMensagem(getString(R.string.msgExclusao));
                                } 别的 {
                                    exibirMensagem(getString(R.string.msgFalhaExclusao));
                                }

                            }
                        })
                .setNegativeButton(getString(R.string.nao),
                        新的 DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                对话框.取消();
                            }
                        });
        builder.create();
        builder.show();

        atualizarLista();

    }

    私人无效 atualizarLista() {

        次 = db.listAll();
        如果(次!= null){
            如果 (times.size() > 0) {
                TimeListAdapter tla = 新的 TimeListAdapter(
                        getApplicationContext(), 次);
                lvTimes.setAdapter(tla);
            }

        }

    }

    私有 AdapterView.OnItemClickListener 选择时间 = 新 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);
            开始活动(意图);




            //preecherDados(t);

        }

    };

    私有 AdapterView.OnItemLongClickListener excluirTime = new AdapterView.OnItemLongClickListener() {

        公共布尔 onItemLongClick(AdapterView arg0,查看 arg1,
                                       int pos, long arg3) {
            excluirTime(times.get(pos).getId());
            返回真;
        }


    };

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

    私人无效exibirMensagem(字符串味精){
        Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
    }

    公共无效 telaCadastrar(查看视图){
        Intent intent = new Intent(this, CadastroTimes.class);
        开始活动(意图);
    }

    public void botaoSair(查看视图) {
        Intent intent = new Intent(this, TelaInicial.class);
        开始活动(意图);
    }
}

【问题讨论】:

  • 如果按钮在CadastroTimes 中,则在CadastroTimes 中而不是在EditarTimes
  • 按钮在 CadastroTimes.class 中,一切正常,我只需要点击一个列表项,调用活动 CadastroTimes 并更改按钮名称。

标签: java android android-intent settext


【解决方案1】:

您可以将按钮标题传递给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 中进行操作

【讨论】:

  • 按钮是空白的,没有任何文字:{我想我不知道该怎么做:{
  • 我添加了可以复制粘贴的代码。请将更改后的代码放入适当的类中。您需要更改 CadastroTimes.java 中的按钮 ID(输入您的按钮 ID 而不是我的 R.id.button)。您的 getExtras 可能会为空。因此,如果您使用我给出的内容更改 EditarTimes 中的代码,这应该可以正常工作。告诉我。
  • 我放弃了,我尝试过,尝试过但无法成功,我正在创建一个新的活动来解决我的问题,感谢您帮助我,很抱歉浪费您的时间。跨度>
【解决方案2】:
//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

     }
}

【讨论】:

    【解决方案3】:

    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
    

    希望对你有帮助

    【讨论】:

      【解决方案4】:

      更改按钮文本:

      1. 使用静态方法从其他Activity调用,直接修改按钮标题。
      2. 最好使用意图功能。
      3. 使用一个接口并实现它,它用于在活动或片段之间以一种即发即弃的原则进行通信。

      【讨论】:

        【解决方案5】:

        现在,我找到你了:

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

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

        【讨论】:

        • 按钮是空白的,没有任何文字:{我想我不知道该怎么做:{
        • 不可能,尝试检查CadastroTimes活动中收到的字符串值,然后它也可以作为文本在按钮上使用。尽快告诉我
        • 接收到的值为null x.x
        • 然后给我CadastroTimes活动(第二个活动)的代码,它的原因按钮没有文字,但如果有null应该是crased。
        • 我有我的列表和一个注册按钮,如果我点击列表,我会打开带有命名按钮“Alterar”的注册屏幕并在数据库上提供更新,如果我点击按钮将打开同一个屏幕,但带有名为“Cadastrar”的按钮并使用插入。
        【解决方案6】:

        好的,所以第一步是获取您想要的按钮并将其设为公共静态对象(并将其放在类的顶部)。

        public static Button button;
        

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

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

        在你的情况下是

        CadastroTimes.salvar.setText("Alterar");
        

        【讨论】:

        • 公共类 CadastroTimes 扩展 AppCompatActivity { 私有时间 t;私人时间数据库;私人 EditText edID;私人 EditText edNome;公共静态按钮萨尔瓦;
        • 是的,它可以跨类使用。让我知道这是否适合您。
        • 我不能使用 salvar.setText("Alterar");在类editarTimes
        • 为什么要制作静态按钮?您应该创建一个接口来访问来自不同类的代码。
        【解决方案7】:

        如果您想更改值,请不要通过意图进行活动,您可以使用文件将值保存到文件,或者您有多个值使用数据库和访问 oncreate 的值来设置文本的值....

        【讨论】:

          【解决方案8】:

          在我的例子中,我必须从 Dialog 样式的 Activity 发送一个 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.
          


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

          【讨论】:

            【解决方案9】:

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

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

            【讨论】:

              【解决方案10】:

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

              在 CadatroTimes.java 中

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

              【讨论】:

                猜你喜欢
                • 2016-04-04
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2019-06-22
                • 1970-01-01
                • 2013-06-08
                相关资源
                最近更新 更多