创建具有交替位置的短信气泡



每次按下按钮时,我都会尝试添加一个TextView。但问题是,我想把它添加到短信应用程序中。第一次单击按钮时,TextView将位于屏幕左侧。下次单击该按钮时,新创建的TextView应该位于右侧。

我尝试使用以下代码,但没有成功。

public void sendMessage(View view){
    EditText editText=(EditText)findViewById(R.id.edit_message);
    String message=editText.getText().toString();

    LinearLayout layout=(LinearLayout)findViewById(R.id.layout01);

    TextView text=new TextView(this);
    text.setText(message);
    text.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
    layout.setOrientation(LinearLayout.VERTICAL);
    if(flag){
        text.setGravity(Gravity.LEFT);          
    }
    else
        text.setGravity(Gravity.RIGHT);
    flag=!flag;
    layout.addView(text);
}

"flag"是在类的开头声明的布尔类型。

编辑-

我是否可以再创建两个布局(一个在左边显示TextView,另一个在右边显示)。但我不知道如何在同一个屏幕上使用不同的布局。

感谢您的帮助

public void sendMessage(View view){
    EditText editText=(EditText)findViewById(R.id.edit_message);
    String message=editText.getText().toString();

    LinearLayout layout=(LinearLayout)findViewById(R.id.layout01);

    TextView text=new TextView(this);
    text.setText(message);
    text.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
    layout.setOrientation(LinearLayout.VERTICAL);
    if(flag){
        text.setGravity(Gravity.LEFT);
        flag=!flag;          
    }
    else
      {
        text.setGravity(Gravity.RIGHT);
    flag=!flag;
      }
    layout.addView(text);
}

最新更新