将 android:layout_gravity="right" 从 TextView 移动到 HorizontalScrollView 将
TextView 重力更改为仅 "center_vertical"
在 Activity.java 中编写一个方法来设置 TextView 中的文本并向右滚动。
当您想在 TextView 中设置文本时,请使用此方法。
示例代码:
XML
<HorizontalScrollView
android:id="@+id/scrollView"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1"
android:scrollbars="none"
android:layout_gravity="right">
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:singleLine="true"
android:text=""
android:gravity="center_vertical"
android:textColor="#666666"
android:textSize="30sp"/>
</HorizontalScrollView>
<Button
android:id="@+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="ClickMe"
android:onClick="btClick"/>
</LinearLayout>
活动.java:
public class MainActivity extends Activity {
private TextView textView;
private HorizontalScrollView scroll;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scroll = (HorizontalScrollView)findViewById(R.id.scrollView);
textView = (TextView) findViewById(R.id.textView2);
SetTextViewText("Inicial Text");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void btClick(View v) {
String text = textView.getText().toString();
int rnd = 1 + (int)(Math.random() * ((9 - 1) + 1));//Get a random number between 1 and 9
text += rnd; //Append random to previous text
SetTextViewText(text); //Set TextView with new text;
}
private void SetTextViewText(String text)// Set text to TexView and scroll all to the right
{
textView.setText(text);
scroll.post(new Runnable() {
public void run() {
scroll.fullScroll(ScrollView.FOCUS_RIGHT);
}
});
}
}
我希望这是你所要求的。