在向另外一个Activity中的LinearLayout动态添加布局的时候,程序运行到addView会闪退,并且无法添加布局
public void new_tv(String message){
LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
ll = (LinearLayout) findViewById(R.id.ll_todo);
add_tv = new TextView(this);
add_tv.setLayoutParams(lparams);
add_tv.setText(message);
add_tv.setTextColor(getResources().getColor(R.color.white));
try {
ll.addView(add_tv);
}catch (Exception e){
e.printStackTrace();
}
}
总代码
import android.app.ActionBar;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class add_goal extends AppCompatActivity {
private EditText et;
private Button btn_send;
private LinearLayout ll;
private TextView add_tv;
private String message;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_goal);
et = (EditText) findViewById(R.id.input_message);
btn_send = (Button) findViewById(R.id.btn_send);
btn_send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
message=et.getText().toString().trim();
new_tv(message);
startActivity(new Intent(add_goal.this,MainActivity.class));
finish();
}
});
}
public void new_tv(String message){
LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
ll = (LinearLayout) findViewById(R.id.ll_todo);
add_tv = new TextView(this);
add_tv.setLayoutParams(lparams);
add_tv.setText(message);
add_tv.setTextColor(getResources().getColor(R.color.white));
try {
ll.addView(add_tv);
}catch (Exception e){
e.printStackTrace();
}
}
}