我对Android很痛苦,我遇到了困境。
我正在尝试使用线性布局来更像按钮,使用不同的按下和长按操作 - 原因是我可以在每个“按钮”上有2个不同格式的文本标签。有点像:
-------------------------
| 2nd | <- Label for long press (regular/smaller type)
| = | <- Label for regular press (bold/larger type)
-------------------------
我发现的帖子解释了如何定期点击线性布局(我使用布局XML中的onClick属性)。但是长按我没有运气。我已经尝试为xml定义一个新的onLongClick属性,如Aleksander Gralak在这里的答案所述:Long press definition at XML layout, like android:onClick does。但是没有这样的运气 - 它看起来像是用于文本视图,我尝试将其更改为线性布局但却失败了。
以下是相关对象:Main.xml
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:clickable="true"
android:focusable="true"
android:background="@drawable/darkgrey_button"
android:onClick="equals" android:longClickable="true" android:id="equalsbutton"
android:focusableInTouchMode="false">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2nd"
android:id="@+id/textView"
android:duplicateParentState="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" = "
android:id="@+id/textView1"
android:duplicateParentState="true"/>
</LinearLayout>
Main.java
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void equals(View view) {
Context context = getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
答案 0 :(得分:6)
在您的布局中添加id
。
<LinearLayout
android:id="@+id/my_button_layout"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
… >
在Main.java
获取LinearLayout
的引用并设置OnLongClickListener
。
LinearLayout buttonLayout = (LinearLayout) findViewById(R.id.my_button_layout);
…
buttonLayout.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
Toast.makeText(Main.this, "Long click!", Toast.LENGTH_SHORT).show();
return true;
}
});