那么,有人知道如何创建以下网格吗?我需要为每个单词设置可点击事件:
如果四个单词不适合一行,那么应该在一行中显示三个:
如果它超过一行n个单词,那么应该在一行中显示n个单词。 有人知道如何实现这个吗?
答案 0 :(得分:2)
您可以使用SpannableString和ClickableSpan。例如,此活动使用您的文本创建TextView并管理每个单词的点击次数:
public class MainActivity extends AppCompatActivity {
Activity activity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
activity = this;
TextView textView = (TextView) findViewById(R.id.textView);
String text = "up down Antidisestablishment over took dropped lighten with from throught fell on up down Antidisestablishment over took dropped lighten with from throught fell on";
String[] textArray = text.split(" ");
SpannableString ss = new SpannableString(text);
int start = 0;
int end = 0;
for(final String item : textArray){
end = start + item.length();
ClickableSpan clickableSpan = new ClickableSpan() {
@Override
public void onClick(View textView) {
Toast.makeText(activity, "Say " + item+ "!", Toast.LENGTH_SHORT).show();
}
@Override
public void updateDrawState(TextPaint ds) {
super.updateDrawState(ds);
ds.setUnderlineText(false);
}
};
ss.setSpan(clickableSpan, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
start += item.length()+1;
}
textView.setText(ss);
textView.setMovementMethod(LinkMovementMethod.getInstance());
textView.setHighlightColor(Color.TRANSPARENT);
}
}
这里是activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity"
android:padding="5dp">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="24sp"
android:textColor="#000000"
android:textColorLink="#000000"/>
</LinearLayout>
如果你点击任何单词,你会弹出这个单词
编辑:为文本辩护使用库android-justifiedtextview
但不是gradle中的库,有旧版本不支持SpannableString
。我建议只需将类JustifyTextView
从git复制到您的项目中。然后,您可以在.xml
中使用此视图,例如:
<com.yourdomain.yourproject.JustifyTextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="24sp"
android:textColor="#000000"
android:textColorLink="#000000"/>
您还可以修改库以保持最后一行不合理。文本中的每个单词仍然可以点击。