Ich setze ein In-Game-Chat-Modul in eine App. Ich bin Hinzufügen von Textnachrichten, wie sie in eine LinearLayout-Ansicht empfangen werden. Ich möchte die Layout-Parameter auf die TextView festlegen, aber der folgende Code stürzt ab und die Fehlermeldungen verwirren mich.
private void addChat(String chat, String when, Boolean mine) {
int leftMargin;
TextView tv = new TextView(this);
llview.addView(tv);
tv.setTextColor(Color.WHITE);
tv.setTextSize(2,25);
tv.setText(chat);
if (mine) {
leftMargin = 5;
tv.setBackgroundColor(0x7C5B77);
}
else {
leftMargin = 50;
tv.setBackgroundColor(0x778F6E);
}
final ViewGroup.MarginLayoutParams lpt =(MarginLayoutParams)tv.getLayoutParams();
lpt.setMargins(leftMargin,lpt.topMargin,lpt.rightMargin,lpt.bottomMargin);
tv.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
}
Wenn er ausgeführt wird, wird der gesamte obige Code ausgeführt, aber er stürzt in der Android-Laufzeit ab als:
03-13 14:15:38.513: E/AndroidRuntime(12985): java.lang.ClassCastException: android.view.ViewGroup$LayoutParams
und wenn man mit dem Debugger durchgeht, werden tatsächlich alle diese Zeilen verarbeitet
aber kotzt dann beim Versuch zu rendern mit einer ebenso kryptischen ausführlichen Ausnahmemeldung:
android.view.ViewGroup$LayoutParams
Was habe ich getan, um diesen Zustand zu erreichen? Was sollte ich tun, um abwechselnd links/rechts eingerückte Meldungen zu haben?
Einfach von unten ersetzen und Folgendes hinzufügen
tv.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
vor
llview.addView(tv);
Nach der Erstellung der Ansicht müssen wir Layoutparameter hinzufügen.
ändern wie folgt
TextView tv = new TextView(this);
tv.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
llview.addView(tv);
tv.setTextColor(Color.WHITE);
tv.setTextSize(2,25);
tv.setText(chat);
if (mine) {
leftMargin = 5;
tv.setBackgroundColor(0x7C5B77);
}
else {
leftMargin = 50;
tv.setBackgroundColor(0x778F6E);
}
final ViewGroup.MarginLayoutParams lpt =(MarginLayoutParams)tv.getLayoutParams();
lpt.setMargins(leftMargin,lpt.topMargin,lpt.rightMargin,lpt.bottomMargin);
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
/*width*/ ViewGroup.LayoutParams.MATCH_PARENT,
/*height*/ ViewGroup.LayoutParams.MATCH_PARENT,
/*weight*/ 1.0f
);
YOUR_VIEW.setLayoutParams(param);